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

后端 未结 14 2519
暗喜
暗喜 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 04:15

    For those who troubled with charset

    I had very special case that the service provider didn't accept charset, and they refuse to change the substructure to allow it... Unfortunately HttpClient was setting the header automatically through StringContent, and no matter if you pass null or Encoding.UTF8, it will always set the charset...

    Today i was on the edge to change the sub-system; moving from HttpClient to anything else, that something came to my mind..., why not use reflection to empty out the "charset"? ... And before i even try it, i thought of a way, "maybe I can change it after initialization", and that worked.

    Here's how you can set the exact "application/json" header without "; charset=utf-8".

    var jsonRequest = JsonSerializeObject(req, options); // Custom function that parse object to string
    var stringContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
    stringContent.Headers.ContentType.CharSet = null;
    return stringContent;
    

    Note: The null value in following won't work, and append "; charset=utf-8"

    return new StringContent(jsonRequest, null, "application/json");
    

    EDIT

    @DesertFoxAZ suggests that also the following code can be used and works fine. (didn't test it myself, if it work's rate and credit him in comments)

    stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    

提交回复
热议问题