简体   繁体   English

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

[英]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... 据我了解,如果我有一个ASP.NET WebApi方法,其签名如下所示......

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. 然后,WebApi模型绑定将查看表单集合,并查看它是否具有与Customer类上的属性名称匹配的条目,并将它们绑定到类的新实例,该实例将传递给该方法。

What if I want to allow some to POST a collection of objects? 如果我想让一些人POST一组对象怎么办? In other words, I want to have a WebApi method that looks like this... 换句话说,我想要一个看起来像这样的WebApi方法......

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

How would the calling code set up the POST? 调用代码如何设置POST?

The same question applies if I want the Customer object to have a property that is a collection, say the customer's orders. 如果我希望Customer对象具有属于集合的属性(例如客户的订单),则同样的问题也适用。 How would the HTTP POST be set up? 如何设置HTTP POST?

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. 问题的原因是我想编写一个控制器,允许使用Delphi的人将信息发布到我的服务器。 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? 有人能帮忙吗?

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: 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();              
         }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM