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

查看:27
本文介绍了如何自定义 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 中有以下代码:

I've got the following code in 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 that InvalidModelStateResponseFactory is set to in order to return whatever you like.

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

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