问题
I'm using ASP.NET Core. One of my controllers calls into services which throw various exceptions. I want to handle them in an exception filter (not middleware).
public class MyHandlerAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext c)
{
if (c.Exception is FooException) {
// redirect with arguments to here
}
else if (c.Exception is FooException) {
// redirect with arguments to there
}
else {
// redirect to main error action without arguments, as 500
}
base.OnException(c);
}
}
Unlike action filters, an exception filter doesn't give me access to the Controller
, so I can't do a c.Result = controller.RedirectTo...()
.
So how do I redirect to my error action?
回答1:
The HttpContext
is exposed on the ExceptionContext
, so you can use it for the redirection.
context.HttpContext.Response.Redirect("...");
There is also a Result
property, but I don't know if it'll be interpreted after the execution of the filter. It's worth a try though:
context.Result = new RedirectResult("...");
If it works, it should also work with RedirectToActionResult
or RedirectToRouteResult
.
来源:https://stackoverflow.com/questions/42338966/redirect-from-exception-filter