gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:45:56 26 4
gpt4 key购买 nike

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

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

..然后 WebApi 模型绑定(bind)将查看表单集合并查看它是否具有与 Customer 类的属性名称匹配的条目,并将它们绑定(bind)到该类的新实例,该实例将传递到方法。

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

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

调用代码将如何设置 POST?

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

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

有人能帮忙吗?

最佳答案

这非常有效。

[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);
}

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

关于c# - ASP.NET WebApi - 如何将集合发布到 WebApi 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21383833/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com