HTTP Post multiple objects through PostAsJsonAsync

2019-05-30 04:26发布

I'm using HttpClient with some WebAPI.

I need to send multiple objects to a POST, here's how my Post method is declared:

public string Post(Models.Client value, App.ControlCenter.Models.Company c) 
{
    ...
}

And here's how I'm calling to the WebAPI:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var s = client
       .PostAsJsonAsync("api/Client/", c)
       .Result
       .Content.ReadAsAsync<App.ControlCenter.Models.RolDTO>().Result;
    return View();
}

What I need to do is send both the Client object and the Company for my Post method to work.

1条回答
smile是对你的礼貌
2楼-- · 2019-05-30 05:18

Client Side

You need to create a DTO class with two properties of types Models.Client and App.ControlCenter.Models.Company

public class DTO.ComplexObject  
{     
  public Models.Client tClientModel { get; set; }

  public App.ControlCenter.Models.Company tCompany{ get; set; }
}

and then fill ComplexObject object (i.e., TComplexObject) and use

HttpResponseMessage tResponse = tHttpClient.PostAsJsonAsync(url,TComplexObject).Result;

API

[HttpPost]
public HttpResponseMessage AddData(DTO.ComplexObject tComplexObject)
{
查看更多
登录 后发表回答