我使用中间件捕获请求异常并像这样写响应
public async Task Invoke(HttpContext context /* other dependencies */)
{
try
{
await next(context);
}
catch (Exception ex)
{
logger.LogError(ex.Message);
await HandleExceptionAsync(context, ex); //write response
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
FanjiaApiResultMessage resultMessage = new FanjiaApiResultMessage()
{
ResultCode = -1,
Data = null,
Msg = exception.Message
};
string result = JsonConvert.SerializeObject(resultMessage);
context.Response.ContentType = "application/json;charset=utf-8";
if (exception is QunarException)
{
context.Response.StatusCode = (int)(exception as QunarException).httpStatusCode;
}
else
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return context.Response.WriteAsync(result);
}
这样的请求模型参数
public class FlightModel {
[JsonProperty("depCity", Required = Required.Always)]
public string DepCity { get; set; }
}
public IActionResult Test(FlightModel model){
return Content("test");
}
当我发布不带DepCity的FlightModel时,我会收到异常
{
"errors": {
"": [
"Required property 'depCity' not found in JSON. Path '', line 6, position 1."
]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "8000000a-0003-ff00-b63f-84710c7967bb"
}
显然中间件没有捕获到异常。
为什么中间件没有被捕获?
答案 0 :(得分:2)
Aspnet核心模型验证失败不会引发异常。它以默认格式提供其自己的响应,其状态码为400(错误请求)。
有几种方法可以覆盖它,包括自定义属性:https://www.jerriepelser.com/blog/validation-response-aspnet-core-webapi/
它看起来像这样:
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new ValidationFailedResult(context.ModelState);
}
}
}
然后像这样添加:
[Route("api/values")]
[ValidateModel]
public class ValuesController : Controller
{
...
}
或者您可以通过覆盖InvalidModelStateResponseFactory
来控制响应的生成,例如以下SO问题:How do I customize ASP.Net Core model binding errors?
这里是一个示例:
services.Configure<ApiBehaviorOptions>(o =>
{
o.InvalidModelStateResponseFactory = actionContext =>
new MyCustomBadRequestObjectResult(actionContext.ModelState);
});