gpt4 book ai didi

asp.net - 考虑到 header 名称,如何将HttpRequestBase转换为HttpRequestMessage?

转载 作者:行者123 更新时间:2023-12-04 05:40:08 27 4
gpt4 key购买 nike

我将HttpRequestBase包装为HttpRequestMessage,这要求将所有 header 都复制过来。但是,由于HttpRequestMessage特定于哪些 header 应用于请求对象与内容对象,因此下面的httpRequest.Headers.Add行有时会引发InvalidOperationException。

public static HttpRequestMessage AsHttpRequestMessage(this HttpRequestBase request) {
Requires.NotNull(request, "request");

var httpRequest = new HttpRequestMessage(new HttpMethod(request.HttpMethod), request.Url);
foreach (string header in request.Headers) {
httpRequest.Headers.Add(header, request.Headers.GetValues(header));
}

if (request.Form != null) {
// Avoid a request message that will try to read the request stream twice for already parsed data.
httpRequest.Content = new FormUrlEncodedContent(request.Form.AsKeyValuePairs());
} else if (request.InputStream != null) {
httpRequest.Content = new StreamContent(request.InputStream);
}

return httpRequest;
}

显然,我希望代码不引发异常,而是将每个 header 适本地应用于适当的对象。我该如何预测呢?我可以使用任何方法来测试 header 的适用性,该 header 不包括生成并捕获异常的 header 吗?

最佳答案

事实证明,这很简单。该片段受ASP.NET's own open sourced source code的启发很大。

/// <summary>
/// Clones an <see cref="HttpWebRequest" /> in order to send it again.
/// </summary>
/// <param name="message">The message to set headers on.</param>
/// <param name="request">The request with headers to clone.</param>
internal static void CopyHeadersFrom(this HttpRequestMessage message, HttpRequestBase request) {
Requires.NotNull(request, "request");
Requires.NotNull(message, "message");

foreach (string headerName in request.Headers) {
string[] headerValues = request.Headers.GetValues(headerName);
if (!message.Headers.TryAddWithoutValidation(headerName, headerValues)) {
message.Content.Headers.TryAddWithoutValidation(headerName, headerValues);
}
}
}

关于asp.net - 考虑到 header 名称,如何将HttpRequestBase转换为HttpRequestMessage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15209284/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com