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

编程入门 行业动态 更新时间:2024-10-12 16:23:55
本文介绍了如何自定义 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 中有以下代码:

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 模型绑定错误?

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

发布评论

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

>www.elefans.com

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