我阅读了building web APIs上的Microsoft文档,但是除了开发自定义模型联编程序外,我没有看到关于如何合并路线和身体参数的示例。我相信我缺少了一些东西,因为开发自定义模型活页夹对于这项常见任务似乎过于刻薄。如何告诉我的应用程序根据路线参数和车身有效载荷创建模型?
Request:
PUT /business/f8e5cf33-40b1-4b8e-8280-b1b60a459154
{"name": "MyBusiness", "street": "123 Main Street"}
Response:
400
{"Id": ["'Id' must not be empty."]}
// BusinessController
[Route("business/{id}")]
[ApiController]
public class BusinessController : Controller {
[HttpPut]
[ProducesResponseType(400)]
public ActionResult PutAsync(BusinessModel business) {
...
}
}
// BusinessModel
class BusinessModel {
// The `[FromRoute]` annotation has no affect
public Guid Id { get; set; }
public string Name { get; set; }
public string Street { get; set; }
}
答案 0 :(得分:0)
您可以在参数部分中分成两个标签。
// BusinessController
[Route("business/{id}")]
[ApiController]
public class BusinessController : Controller {
[HttpPut]
[ProducesResponseType(400)]
public ActionResult PutAsync([FromBody]BusinessModel business, [FromRoute] int id) {
...
}
}
然后将该ID分配给模型(如果它是模型的一部分)。
答案 1 :(得分:0)
正确的代码如下(婴儿车区分大小写,因此路线中的一辆需要与您的财产相匹配)
[Route("business/{Id}")]
[ApiController]
public class BusinessController : Controller {
[HttpPut]
[ProducesResponseType(400)]
public ActionResult PutAsync(BusinessModel business) {
...
}
}
// BusinessModel
class BusinessModel {
[FromRoute]
public Guid Id { get; set; }
[FromForm]
public string Name { get; set; }
[FromForm]
public string Street { get; set; }
}