简体   繁体   English

ASP.NET Core modelbinder 将请求正文绑定到模型的一个属性

[英]ASP.NET Core modelbinder binding request body to one property of model

I'm trying to bind this request body to the Data property of class CreateCommand :我正在尝试将此请求正文绑定到类CreateCommandData属性:

public class CreateCommand<TCommand, TEntity> : IRequest<int>
    where TCommand : ICommand
    where TEntity : Entity, IAggregateRoot
{
    [FromBody] // this attribute is not working.
    public TCommand Data { get; set; }
    public CreateCommand() { }
}

[HttpPost]
public async Task<ActionResult<TicketVM1>> PostProduce(CreateCommand<TicketV1Command, Produce> createCommond)
{
    var id = await _mediator.Send(createCommond);

    return CreatedAtAction("GetProduce", new { id = id });
}

Can I use property as the root of request body?我可以使用属性作为请求主体的根吗?

To successfully achieve this binding move the attribute to method signature要成功实现此绑定,请将属性移动到方法签名

public class CreateCommand<TCommand, TEntity> : IRequest<int>
    where TCommand : ICommand
    where TEntity : Entity, IAggregateRoot
{
    public TCommand Data { get; set; }
    public CreateCommand() { }
}

[HttpPost]
public async Task<ActionResult<TicketVM1>> PostProduce([FromBody]CreateCommand<TicketV1Command, Produce> createCommond)
{
    var id = await _mediator.Send(createCommond);

    return CreatedAtAction("GetProduce", new { id = id });
}

Now when posting data make sure to encapsulate it all inside a data object.现在,在发布数据时,请确保将其全部封装在数据对象中。 This may become your final body这可能会成为你最后的身体

{
   "Data":
   {
      "Foo": "bar"
   }
}

You can however bind to it directly by:但是,您可以通过以下方式直接绑定到它:

public async Task<ActionResult<TicketVM1>> PostProduce([FromBody]CreateCommand<TicketV1Command, Produce>.Data createCommond)

now you can post data as-is现在您可以按原样发布数据

{
    "Foo": "Bar"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM