5 asp.net model-binding asp.net-web-api
我阅读了 Microsoft 关于构建 Web API的文档,但除了开发自定义模型绑定器之外,我没有看到有关如何合并路由和正文参数的示例。我相信我错过了一些东西,因为开发自定义模型绑定器对于这个常见任务来说似乎有点过分了。如何告诉我的应用程序从路由参数和主体有效负载创建模型?
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; }
}
Run Code Online (Sandbox Code Playgroud)
小智 0
您可以在参数部分分隔两个标签。
// BusinessController
[Route("business/{id}")]
[ApiController]
public class BusinessController : Controller {
[HttpPut]
[ProducesResponseType(400)]
public ActionResult PutAsync([FromBody]BusinessModel business, [FromRoute] int id) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
然后将该 id 分配给模型(如果它是模型的一部分)。
| 归档时间: |
|
| 查看次数: |
3892 次 |
| 最近记录: |