【发布时间】:2021-10-07 00:07:28
【问题描述】:
我正在为我的新 REST API 项目使用 ASP.NET Core。我添加了一个ApiExceptionFilter 来获取系统无法处理的任何异常。
但过滤器无法从 [Required] 属性中捕获异常。 该请求将得到 400 响应和消息。
{
"errors": {
"XXX": [
"The XXX field is required."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-fa92d07cf6c8694c87febb276786aada-6f9327722d0cb84b-00"
}
我想像ApiExcetionFilter 那样自定义错误消息。
我尝试实现UseExceptionHandler,但没有成功。
app.UseExceptionHandler(c => c.Run(async context =>
{
var exception = context.Features
.Get<Exception>();
var response = new { error = exception.Message };
await context.Response.WriteAsJsonAsync(response);
}));
我必须实现其他功能还是我做错了什么? 谢谢
【问题讨论】: