我将 an 包装HttpRequestBase
为HttpRequestMessage
,这需要复制所有标题。但由于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;
}
显然,我希望我的代码不抛出异常,而是将每个标头适当地应用于适当的对象。我怎么能预测这个?有没有什么方法可以用来测试没有生成和捕获异常的标头的适用性?