。NET Core 3-混合路径和主体数据的自定义模型绑定

问题描述 投票:-1回答:1

我有一个具有3个属性的模型,我想使用ASP.NET Core进行绑定和验证。从这3个属性中,应从POSTed JSON主体绑定2个,而应从路由参数绑定第三个:

public class CustomModel
{
    public string Id_Model { get; set; } //Bind it from RouteData
    public string Value { get; set; } //Bind it from Body
    public string Type { get; set; } //Bind it from Body
}

[Route("[controller]")]
public CustomController : ControllerBase
{
    [HttpPost("{Id_Model}")]
    public IActionResult Post(CustomModel model)
    {
        return Ok();
    }
}

事实是,我不想在模型本身上添加任何属性(它将在另一个程序集中声明,并且我不希望在此程序集中来自Microsoft.AspNetCore的依赖项。

我试图创建一个CustomModelBinder,但是我只停留在bindingContext.ValueProvider中可用的Route数据上,我不知道如何获取Body / Json数据。

我尝试使用FormValueProviderFactory,并用new ValueProviderFactoryContext(bindingContext.ActionContext)实例化一个,但是生成的提供者始终是null

任何想法如何进行这种混合装订?

c# asp.net-mvc asp.net-core .net-core model-binding
1个回答
0
投票

我不确定您是否是这个意思:

[HttpPost("{Id_Model}")]
public IActionResult Post([FromBody] CustomModel model, string Id_Model)
{
    model.Id_Model = Id_Model;

    // rest of the code as you wish

    return Ok();
}

因此,您可以在POST将此端点的以下内容捕获到它:http://localhost:63676/Custom/100

enter image description here

希望这有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.