如何自定义ASP.Net Core模型绑定错误? [英] How do I customize ASP.Net Core model binding errors?

查看:329
本文介绍了如何自定义ASP.Net Core模型绑定错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想从我的Web API(Asp.net Core 2.1)返回标准化的错误响应,但似乎无法弄清楚如何处理模型绑定错误.

I would like to return only standardized error responses from my Web API (Asp.net Core 2.1), but I can't seem to figure out how to handle model binding errors.

该项目是通过"ASP.NET Core Web应用程序">"API"模板创建的.我有一个简单的动作定义为:

The project is just created from the "ASP.NET Core Web Application" > "API" template. I've got a simple action defined as:

[Route("[controller]")]
[ApiController]
public class MyTestController : ControllerBase
{
    [HttpGet("{id}")]
    public ActionResult<TestModel> Get(Guid id)
    {
        return new TestModel() { Greeting = "Hello World!" };
    }
}

public class TestModel
{
    public string Greeting { get; set; }
}

如果我使用无效的Guid(例如https://localhost:44303/MyTest/asdf)请求此操作,则会返回以下响应:

If I make a request to this action with an invalid Guid (eg, https://localhost:44303/MyTest/asdf), I get back the following response:

{
    "id": [
        "The value 'asdf' is not valid."
    ]
}

我在Startup.Configure中有以下代码:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    JsonErrorMiddleware.CreateSingleton(env);

    if (!env.IsDevelopment())
    {
        app.UseHsts();
    }

    app
        .UseHttpsRedirection()
        .UseStatusCodePages(async ctx => { await JsonErrorMiddleware.Instance.Invoke(ctx.HttpContext); })
        .UseExceptionHandler(new ExceptionHandlerOptions() { ExceptionHandler = JsonErrorMiddleware.Instance.Invoke })
        .UseMvc()
}

JsonErrorMiddleware只是一个将错误转换为我想返回的正确形状并将其放入响应中的类.完全没有因为模型绑定错误而调用它(没有抛出Exception且没有调用UseStatusCodePages.)

JsonErrorMiddleware is simply a class that converts errors to the correct shape I want to return and puts them into the response. It is not getting called at all for the model binding errors (no Exception is thrown and UseStatusCodePages is not called).

我该如何绑定到模型绑定中,以便为项目中的所有操作提供标准化的错误响应?

How do I hook into the model binding to provide a standardized error response across all actions in my project?

我已经阅读了很多文章,但是它们似乎都在讨论全局异常处理或验证错误.

I've read a bunch of articles, but they all seem to either discuss global exception handling or validation errors.

推荐答案

值得一提的是,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.

这篇关于如何自定义ASP.Net Core模型绑定错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆