我一直试图通过简单地返回404来制作异常过滤器。不幸的是,它似乎根本不返回404,而是抛出500.
API控制器:
[HttpGet("{id}")]
[ItemNotFoundExceptionFilter]
public async Task<IActionResult> Get(int id)
{
var _service = new CustomExeptionService();
_service.ThrowItemNotFoundException();
return Ok();
}
自定义异常服务:
public class CustomExeptionService
{
public void ThrowItemNotFoundException()
{
throw new ItemNotFoundException("This is a custom Exception.");
}
}
public class ItemNotFoundException : Exception
{
public ItemNotFoundException(string message) : base(message) { }
public ItemNotFoundException(string message, Exception ex) : base(message, ex) { }
}
异常过滤器属性:
public class ItemNotFoundExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
HandleCustomException(context);
base.OnException(context);
}
private void HandleCustomException(ExceptionContext context)
{
if (context.Exception.GetType() == typeof(ItemNotFoundException))
{
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
}
}
}
答案 0 :(得分:0)
快来找出MVC 6不存在HttpResponseException。
David Fowlers回应: https://twitter.com/YuvalItzchakov/status/614094855367581696
未处理的异常流出管道。你必须编写自己的中间件来做你想做的事情。
答案 1 :(得分:0)
我今天遇到了同样的问题。如果您清除异常,我认为您的代码将起作用。例如:
public override void OnException(ExceptionContext context)
{
if (context.Exception.GetType() == typeof(TokenExpiredException))
{
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Exception = null;
}
base.OnException(context);
}