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

前端 未结 9 507
感动是毒
感动是毒 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 17:05

    The generic HttpRequestMessage has been removed. This :

    new HttpRequestMessage(widget)
    

    will no longer work.

    Instead, from this post, the ASP.NET team has included some new calls to support this functionality:

    HttpClient.PostAsJsonAsync(T value) sends “application/json”
    HttpClient.PostAsXmlAsync(T value) sends “application/xml”
    

    So, the new code (from dunston) becomes:

    Widget widget = new Widget()
    widget.Name = "test"
    widget.Price = 1;
    
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:44268");
    client.PostAsJsonAsync("api/test", widget)
        .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );
    

提交回复
热议问题