【发布时间】:2016-07-20 15:22:14
【问题描述】:
问题
我需要找到一种方法将类上的属性绑定到 ASP.NET Core MVC 中的 http 请求的主体,并且我需要在不使用 FromBody 属性的情况下做到这一点。
我有以下课程:
public class SaveEntity
{
// This property should be bound from the URL.
public Guid Id { get; set; }
// This property should be bound from the body.
public SaveEntityParameters Payload { get; set; }
}
这是我打算在控制器中使用它的方式。
[Route("api/v1/[controller]")]
public class EntitiesController : Controller
{
readonly IBus _bus;
public EntitiesController(IBus bus)
{
if (bus == null)
throw new ArgumentNullException(nameof(bus));
_bus = bus;
}
[HttpPut("{id}")]
public async Task<IActionResult> Put(SaveEntity command)
{
var response = await _bus.SendAsync(command);
return Ok(response);
}
}
SaveEntity 类位于不依赖于 MVC 的类库中,这就是为什么 FromBody 属性不可用的原因。如何将SaveEntity 类的Payload 属性绑定到正文,同时保持Id 属性绑定到url?
不太理想的解决方法
我考虑过拆分 Id 和 Payload 属性。然后我可以这样做:
[HttpPut("{id}")]
public async Task<IActionResult> Put(Guid id, [FromBody]SaveEntityParameters payload)
{
SaveEntity command = new SaveEntity {Id = id, Payload = payload};
var response = await _bus.SendAsync(command);
return Ok(response);
}
但是我必须先手动分配SaveEntity 实例的属性,然后才能使用它。如果可能的话,我想避免手动分配,因为这种类型的事情会在多个控制器中发生。
【问题讨论】:
标签: asp.net-core-mvc