ASP.NET WebApi - 如何将集合发布到WebApi方法?

Avr*_*oel 5 c# asp.net http asp.net-web-api

据我了解,如果我有一个ASP.NET WebApi方法,其签名如下所示......

public HttpResponseMessage PostCustomer(Customer customer) {
  // code to handle the POSTed customer goes here
}
Run Code Online (Sandbox Code Playgroud)

..then的的WebAPI模型绑定会去翻形式收集和查看它是否具有匹配Customer类的属性的名称的条目,并将其绑定到的类,它获取传递给方法的新实例.

如果我想让一些人POST一组对象怎么办?换句话说,我想要一个看起来像这样的WebApi方法......

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

调用代码如何设置POST?

如果我希望Customer对象具有属于集合的属性(例如客户的订单),则同样的问题也适用.如何设置HTTP POST?

问题的原因是我想编写一个控制器,允许使用Delphi的人将信息发布到我的服务器.不知道这是否相关,但我想最好提一下以防万一.我可以看到他如何为单个对象执行此操作(请参阅第一个代码段),但无法看到他将如何为集合执行此操作.

有人能帮忙吗?

Sat*_*dav 1

这非常有效。

[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);
}
Run Code Online (Sandbox Code Playgroud)

POST 多个实体的客户端代码:

 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();              
         }
}
Run Code Online (Sandbox Code Playgroud)