9

我将 an 包装HttpRequestBaseHttpRequestMessage,这需要复制所有标题。但由于HttpRequestMessage特别关注哪些标头适用于请求对象和内容对象,因此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;
}

显然,我希望我的代码不抛出异常,而是将每个标头适当地应用于适当的对象。我怎么能预测这个?有没有什么方法可以用来测试没有生成和捕获异常的标头的适用性?

4

2 回答 2

15

事实证明这很简单。这个片段的灵感来自ASP.NET 自己的开源源代码

/// <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);
        }
    }
}
于 2013-03-05T23:20:25.970 回答
1

您应该能够使用 TryAddWithoutValidation 而不是 Add 来避免抛出。您需要注意是否调用 GetBufferlessStream 取决于您是否要缓冲请求。请参阅以下类中的 ConvertRequest 方法:http: //aspnetwebstack.codeplex.com/SourceControl/changeset/view/4764b0111b91#src/System.Web.Http.WebHost/HttpControllerHandler.cs

于 2013-03-05T08:09:04.703 回答