自定义模型绑定路线和主体数据的绑定

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

我有一个具有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-core-mvc model-binding
2个回答
1
投票

我尝试创建一个CustomModelBinder,但是我只绑定了bindingContext.ValueProvider中可用的Route数据,并且我不知道如何获取Body / Json数据。

您可以在自定义模型活页夹中阅读请求正文:

public class testDtoEntityBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            bindingContext.HttpContext.Request.EnableBuffering();
            var body = bindingContext.HttpContext.Request.Body;
            body.Position = 0;


            string raw = new System.IO.StreamReader(body).ReadToEnd();

            //now read content from request content and fill your model 
            var result = new testDto
            {
                A = "",
                B = 1,
            };


            bindingContext.Result = ModelBindingResult.Success(result);
            return Task.CompletedTask;
        }
    }

在模型上如下使用:

[ModelBinder(BinderType = typeof(testDtoEntityBinder))]

您也可以从bindingContext.HttpContext.Request获取路线数据。


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(model);
}

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

enter image description here

希望这有所帮助。

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