[英]Inconsistent error response in .NET 6 Web API application
I am not able to find how to throw exceptions as they are generated by .NET 6 Web API.我无法找到如何抛出异常,因为它们是由 .NET 6 Web API 生成的。 If I return
BadRequest(ModelState)
with added errors I am not getting same message with status, type, title etc. By default .NET generates this kind of errors when validation error occurs:如果我返回
BadRequest(ModelState)
并添加错误,我不会收到与状态、类型、标题等相同的消息。默认情况下,.NET 在发生验证错误时会生成此类错误:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-488f8c0057223cbba92fc1fbfc8865d8-2341d7aba29d098f-00",
"errors": {
"$": [
"The JSON object contains a trailing comma at the end which is not supported in this mode. Change the reader options. Path: $ | LineNumber: 7 | BytePositionInLine: 0."
],
"model": [
"The model field is required."
]
}
} }
I want to configure my application to respond with the same error JSON, or I want to configure so it will respond with the custom JSON fields.我想将我的应用程序配置为使用相同的错误 JSON 进行响应,或者我想配置它以使用自定义 JSON 字段进行响应。
I tried to add a middleware that will catch exceptions, but it does not handle model errors (which are handled by framework by itself).我尝试添加一个可以捕获异常的中间件,但它不处理 model 错误(由框架自行处理)。 How can I handle errors globally, or how can I throw exceptions that will be treated the same as framework handles them?
如何全局处理错误,或者如何抛出与框架处理它们相同的异常? Any documentation/tutorial links are welcome!
欢迎任何文档/教程链接!
You can disable default bad request responses like the following code:您可以禁用默认的错误请求响应,如下面的代码:
builder.Services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
So you can return any model you want in BadRequest
.因此,您可以在
BadRequest
中返回您想要的任何 model 。 However, you then have to do the model validation yourself in each endpoint like:但是,您必须自己在每个端点中进行 model 验证,例如:
[HttpPost(Name = "Post1")]
public IActionResult Post1(Model1 model)
{
if (!ModelState.IsValid)
return BadRequest(new CustomApiResponse());
...
}
[HttpPost(Name = "Post2")]
public IActionResult Post2(Model2 model)
{
if (!ModelState.IsValid)
return BadRequest(new CustomApiResponse();
...
}
If you want to return a global JSON structure, you can create a filter with the ActionFilterAttribute
and use it for all your endpoints so you don't need to do model validation on every endpoint.如果您想返回一个全局 JSON 结构,您可以使用
ActionFilterAttribute
创建一个过滤器并将其用于您的所有端点,这样您就不需要在每个端点上进行 model 验证。
Custom Action Filter:自定义动作过滤器:
public class CustomValidationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(new GlobalApiResponse(context.ModelState));
}
base.OnActionExecuting(context);
}
}
You need to register your custom filter in Program.cs您需要在 Program.cs 中注册您的自定义过滤器
builder.Services.AddControllers(options =>
{
options.Filters.Add(typeof(CustomValidationFilterAttribute));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.