Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET WebApi - how do I post a collection to a WebApi method?

As I understand it, if I have an ASP.NET WebApi method whose signature looks like this...

public HttpResponseMessage PostCustomer(Customer customer) {
  // code to handle the POSTed customer goes here
}

..then the WebApi model binding will look through the form collection and see if it has entries that match the names of the properties on the Customer class, and bind them to a new instance of the class, which gets passed in to the method.

What if I want to allow some to POST a collection of objects? In other words, I want to have a WebApi method that looks like this...

public HttpResponseMessage PostCustomers(IEnumerable<Customer> customers) {
  // code to handle the POSTed customers goes here
}

How would the calling code set up the POST?

The same question applies if I want the Customer object to have a property that is a collection, say the customer's orders. How would the HTTP POST be set up?

The reason for the question is that I want to write a controller that will allow someone using Delphi to POST information to my server. Don't know if that is relevant, but thought I better mention it in case. I can see how he could do this for a single object (see first code snippet), but can't see how he would do it for the collection.

Anyone able to help?

like image 616
Avrohom Yisroel Avatar asked Nov 11 '22 14:11

Avrohom Yisroel


1 Answers

This works perfectly.

[ResponseType(typeof(Customer))]
public async Task<IHttpActionResult> PostCustomer(IEnumerable<Customer> customers)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    db.Customers.AddRange(customers);
    await db.SaveChangesAsync();
    return StatusCode(HttpStatusCode.Created);
}

Client code to POST multiple entities:

 public async Task<string> PostMultipleCustomers()
 {
        var customers = new List<Customer>
        {
            new Customer { Name = "John Doe" },
            new Customer { Name = "Jane Doe" },
        };
        using (var client = new HttpClient())
        {
            HttpResponseMessage response = await client.PostAsJsonAsync("http://<Url>/api/Customers", customers);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                return result;
            }
            return response.StatusCode.ToString();              
         }
}
like image 113
Satish Yadav Avatar answered Nov 14 '22 23:11

Satish Yadav