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

编程入门 行业动态 更新时间:2024-10-12 18:18:45
本文介绍了如何自定义ASP.Net Core模型绑定错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I would like to return only standardized error responses from my Web API (Asp 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(例如localhost:44303/MyTest/asdf)请求此操作,则会返回以下响应:

If I make a request to this action with an invalid Guid (eg, 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模型绑定错误?

本文发布于:2023-11-14 03:57:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586149.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   绑定   模型   错误   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!