How do you set the Content-Type header for an HttpClient request?

后端 未结 14 2229
暗喜
暗喜 2020-11-22 03:57

I\'m trying to set the Content-Type header of an HttpClient object as required by an API I am calling.

I tried setting the Content-Ty

14条回答
  •  广开言路
    2020-11-22 04:38

    .Net tries to force you to obey certain standards, namely that the Content-Type header can only be specified on requests that have content (e.g. POST, PUT, etc.). Therefore, as others have indicated, the preferred way to set the Content-Type header is through the HttpContent.Headers.ContentType property.

    With that said, certain APIs (such as the LiquidFiles Api, as of 2016-12-19) requires setting the Content-Type header for a GET request. .Net will not allow setting this header on the request itself -- even using TryAddWithoutValidation. Furthermore, you cannot specify a Content for the request -- even if it is of zero-length. The only way I could seem to get around this was to resort to reflection. The code (in case some else needs it) is

    var field = typeof(System.Net.Http.Headers.HttpRequestHeaders)
        .GetField("invalidHeaders", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static) 
      ?? typeof(System.Net.Http.Headers.HttpRequestHeaders) 
        .GetField("s_invalidHeaders", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
    if (field != null)
    {
      var invalidFields = (HashSet)field.GetValue(null);
      invalidFields.Remove("Content-Type");
    }
    _client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "text/xml");
    

    Edit:

    As noted in the comments, this field has different names in different versions of the dll. In the source code on GitHub, the field is currently named s_invalidHeaders. The example has been modified to account for this per the suggestion of @David Thompson.

提交回复
热议问题