【问题标题】:Bind a property to the body of a request without the FromBody attribute in ASP.NET Core MVC在 ASP.NET Core MVC 中将属性绑定到没有 FromBody 属性的请求正文
【发布时间】: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?

不太理想的解决方法

我考虑过拆分 IdPayload 属性。然后我可以这样做:

[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


    【解决方案1】:

    这并不能回答您的问题,但您也可以执行以下操作:

    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&lt;IActionResult&gt; Put(SaveEntityDTO saveEntityDTO)

    我认为理想情况下你需要一个自定义模型绑定器,它知道绑定SaveEntity

    【讨论】:

    • 感谢您提供此信息。是的,这个解决方案似乎类似于我的问题中的解决方法。但是,如果我最终在几个不同的控制器方法中使用相同的 SaveEntity 类,这将派上用场。我认为您在自定义模型绑定器上走在了正确的轨道上。我也对此进行了研究,但找不到一种优雅的方式将嵌套类型与它绑定。
    猜你喜欢
    • 2020-01-08
    • 2018-08-30
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    相关资源
    最近更新 更多