且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何自定义ASP.Net Core模型绑定错误?

更新时间:2023-02-14 16:11:52

值得一提的是,ASP.NET Core 2.1添加了[ApiController]属性,该属性通过返回一个BadRequestObjectResult来自动处理模型验证错误. ModelState传入.换句话说,如果用该属性装饰控制器,则不再需要进行if (!ModelState.IsValid)检查.

It's worth mentioning that ASP.NET Core 2.1 added the [ApiController] attribute, which among other things, automatically handles model validation errors by returning a BadRequestObjectResult with ModelState passed in. In other words, if you decorate your controllers with that attribute, you no longer need to do the if (!ModelState.IsValid) check.

此外,该功能也是可扩展的.在Startup中,您可以添加:

Additionally, the functionality is also extensible. In Startup, you can add:

services.Configure<ApiBehaviorOptions>(o =>
{
    o.InvalidModelStateResponseFactory = actionContext =>
        new BadRequestObjectResult(actionContext.ModelState);
});

以上是默认情况下已经发生的事情,但是您可以在其中设置InvalidModelStateResponseFactory的lambda进行自定义,以返回所需的内容.

The above is just what already happens by default, but you can customize the lambda there that InvalidModelStateResponseFactory is set to in order to return whatever you like.