简体   繁体   English

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

[英]How do I customize ASP.Net Core model binding errors?

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

The project is just created from the "ASP.NET Core Web Application" > "API" template.该项目刚刚从“ASP.NET Core Web 应用程序”>“API”模板创建。 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; }
}

If I make a request to this action with an invalid Guid (eg, https://localhost:44303/MyTest/asdf ), I get back the following response:如果我使用无效的 Guid(例如https://localhost:44303/MyTest/asdf )向此操作发出请求,我会得到以下响应:

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

I've got the following code in Startup.Configure :我在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 is simply a class that converts errors to the correct shape I want to return and puts them into the response. JsonErrorMiddleware只是一个类,它将错误转换为我想要返回的正确形状并将它们放入响应中。 It is not getting called at all for the model binding errors (no Exception is thrown and UseStatusCodePages is not called).这是没有得到所谓的在所有的模型绑定错误(没有Exception被抛出UseStatusCodePages不叫)。

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.我读过很多文章,但它们似乎都在讨论全局异常处理或验证错误。

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.值得一提的是,ASP.NET Core 2.1 添加了[ApiController]属性,该属性通过返回传入ModelStateBadRequestObjectResult自动处理模型验证错误。换句话说,如果您使用该属性装饰您的控制器,您就不需要不再需要进行if (!ModelState.IsValid)检查。

Additionally, the functionality is also extensible.此外,该功能也是可扩展的。 In Startup , you can add:Startup ,您可以添加:

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

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.以上只是默认情况下已经发生的情况,但您可以自定义InvalidModelStateResponseFactory设置的 lambda以返回您喜欢的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM