我一直試圖通過僅僅返回一個404來使一個異常過濾器工作。不幸的是,它似乎並沒有返回404,而是拋出500.ASP.NET Core 1.0異常過濾器無法返回404
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;
}
}
}
如果你在你的'OnException'方法中放置一個斷點,它會被調用嗎? – krillgar
是的OnException確實被調用。實際上HandleCustomException也被調用,並且它進入了if。 'context.HttpContext.Response.StatusCode'也被正確設置爲404,但在通過網絡的響應中,我仍然看到500而不是404。 – allencoded