title: How to convert HttpRequestBase to HttpRequestMessage, considering header names?
body: <p>I am wrapping an <code>HttpRequestBase</code> as an <code>HttpRequestMessage</code>, which requires all the headers be copied over. But since <code>HttpRequestMessage</code> is particular about which headers apply to the request object vs. the Content object, the <code>httpRequest.Headers.Add</code> line below sometimes throws InvalidOperationException.</p>
  
  <pre><code>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;
  }
  </code></pre>
  
  <p>Obviously I'd like my code to not throw exceptions, but rather appropriately apply each header to the appropriate object. How can I predict this? Is there any method I can use to test the applicability of a header short of one that generates and catches exceptions?</p>