gpt4 book ai didi

c# - asp.net core 中间件无法捕获 newtonsoft 异常

转载 作者:行者123 更新时间:2023-11-30 21:30:36 25 4
gpt4 key购买 nike

我使用中间件捕获请求异常并像这样编写响应

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"
}

显然异常没有被中间件捕获。

为什么中间件没有被捕获?

最佳答案

Aspnet Core 模型验证失败不会引发异常。它以默认格式提供自己的响应,状态代码为 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);
});

关于c# - asp.net core 中间件无法捕获 newtonsoft 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54140635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com