jsasuga
jsasuga

Reputation: 68

HTTP Post multiple objects through PostAsJsonAsync

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.

Upvotes: 1

Views: 3270

Answers (1)

alj
alj

Reputation: 170

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)
{

Upvotes: 3

Related Questions