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

后端 未结 14 2411
暗喜
暗喜 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:33

    If you don't mind a small library dependency, Flurl.Http [disclosure: I'm the author] makes this uber-simple. Its PostJsonAsync method takes care of both serializing the content and setting the content-type header, and ReceiveJson deserializes the response. If the accept header is required you'll need to set that yourself, but Flurl provides a pretty clean way to do that too:

    using Flurl.Http;
    
    var result = await "http://example.com/"
        .WithHeader("Accept", "application/json")
        .PostJsonAsync(new { ... })
        .ReceiveJson();
    

    Flurl uses HttpClient and Json.NET under the hood, and it's a PCL so it'll work on a variety of platforms.

    PM> Install-Package Flurl.Http
    

提交回复
热议问题