API 异常过滤器 returns ASP.NET MVC 中异常的 200 响应代码
API exception filter returns 200 response code on exception in ASP.NET MVC
我为 API 编写了一个异常过滤器来处理 API:
中抛出的异常
using System;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ApiExceptionFilter : ExceptionFilterAttribute {
public override void OnException(ExceptionContext context) {
// First, generate the status code based on the exception type
HttpStatusCode status = context.Exception switch {
UnauthorizedAccessException => HttpStatusCode.Unauthorized,
ArgumentException => HttpStatusCode.BadRequest,
MissingHeaderException => HttpStatusCode.BadRequest,
NotFoundException => HttpStatusCode.NotFound,
_ => HttpStatusCode.InternalServerError,
};
// Next, inject the status code and exception message into
// a new error response and set the result with it
context.Result = new JsonResult(new ErrorResponse {
StatusCode = status,
Message = context.Exception.Message
});
// Finally, call the base function
base.OnException(context);
}
}
此函数按预期拦截异常,但我遇到的问题是它总是 returns OK 响应。如何确保响应包含异常消息并且响应代码是非 200 值?
而不是 returning JsonResult
- 它不会公开要设置的状态代码 属性 - return 一个 ExceptionResult
并设置状态代码如下:
context.Result = new ExceptionResult(context.Exception, true)
{ StatusCode = status };
如果您仍想使用 ErrorResponse 对象,只需使用一个对象结果:
context.Result = new ObjectResult(new ErrorResponse {
StatusCode = status,
Message = context.Exception.Message
})
// set status code on result
{ StatusCode = status };
我为 API 编写了一个异常过滤器来处理 API:
中抛出的异常using System;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ApiExceptionFilter : ExceptionFilterAttribute {
public override void OnException(ExceptionContext context) {
// First, generate the status code based on the exception type
HttpStatusCode status = context.Exception switch {
UnauthorizedAccessException => HttpStatusCode.Unauthorized,
ArgumentException => HttpStatusCode.BadRequest,
MissingHeaderException => HttpStatusCode.BadRequest,
NotFoundException => HttpStatusCode.NotFound,
_ => HttpStatusCode.InternalServerError,
};
// Next, inject the status code and exception message into
// a new error response and set the result with it
context.Result = new JsonResult(new ErrorResponse {
StatusCode = status,
Message = context.Exception.Message
});
// Finally, call the base function
base.OnException(context);
}
}
此函数按预期拦截异常,但我遇到的问题是它总是 returns OK 响应。如何确保响应包含异常消息并且响应代码是非 200 值?
而不是 returning JsonResult
- 它不会公开要设置的状态代码 属性 - return 一个 ExceptionResult
并设置状态代码如下:
context.Result = new ExceptionResult(context.Exception, true)
{ StatusCode = status };
如果您仍想使用 ErrorResponse 对象,只需使用一个对象结果:
context.Result = new ObjectResult(new ErrorResponse {
StatusCode = status,
Message = context.Exception.Message
})
// set status code on result
{ StatusCode = status };