How to use System.Net.HttpClient to post a complex type?

前端 未结 9 515
感动是毒
感动是毒 2020-11-29 16:31

I have a custom complex type that I want to work with using Web API.

public class Widget
{
    public int ID { get; set; }
    public string Name { get; set;         


        
9条回答
  •  庸人自扰
    2020-11-29 16:50

    If you want the types of convenience methods mentioned in other answers but need portability (or even if you don't), you might want to check out Flurl [disclosure: I'm the author]. It (thinly) wraps HttpClient and Json.NET and adds some fluent sugar and other goodies, including some baked-in testing helpers.

    Post as JSON:

    var resp = await "http://localhost:44268/api/test".PostJsonAsync(widget);
    

    or URL-encoded:

    var resp = await "http://localhost:44268/api/test".PostUrlEncodedAsync(widget);
    

    Both examples above return an HttpResponseMessage, but Flurl includes extension methods for returning other things if you just want to cut to the chase:

    T poco = await url.PostJsonAsync(data).ReceiveJson();
    dynamic d = await url.PostUrlEncodedAsync(data).ReceiveJson();
    string s = await url.PostUrlEncodedAsync(data).ReceiveString();
    

    Flurl is available on NuGet:

    PM> Install-Package Flurl.Http
    

提交回复
热议问题