我有一个具有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
。
任何想法如何进行这种混合装订?
我尝试创建一个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
获取路线数据。