我需要找到一种方法将类的属性绑定到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
属性不可用。如何将Payload
类的SaveEntity
属性绑定到正文,同时保持绑定到url的Id
属性?
我考虑过分割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
实例的属性才能使用它。如果可能的话,我想避免手动分配,因为这类事情将在几个控制器中发生。
答案 0 :(得分:0)
这不能解答您的问题,但您也可以执行以下操作:
public class SaveEntityDTO
{
[FromRoute]
public Guid Id { get; set; }
[FromBody]
public SaveEntityParameters Payload { get; set; }
public SaveEntity GetEntity()
{
return new SaveEntity { Id = Id, Payload = Payload };
}
}
行动:public async Task<IActionResult> Put(SaveEntityDTO saveEntityDTO)
我认为理想情况下你需要一个知道绑定SaveEntity