用法: filterContext.RedirectToAction("Login", "Account");
这是我编写的帮助程序类,其中编写了一些扩展方法,以在更多地方提供RedirectToAction功能。这对于OP来说为时已晚,但希望它能对某人有所帮助!
public static class RedirectHelper
{
public static void RedirectToAction(this HttpResponseBase response, String action, String controller, object routeValues = null, bool endResponse = false)
{
response.RedirectToRoute(CreateRoute(action, controller, routeValues));
if (endResponse) response.End();
}
public static void RedirectToAction(this HttpResponse response, String action, String controller, object routeValues = null, bool endResponse = false)
{
response.RedirectToRoute(CreateRoute(action, controller, routeValues));
if (endResponse) response.End();
}
public static void RedirectToAction(this ActionExecutingContext filterContext, String action, String controller, object routeValues = null, bool endResponse = false)
{
if (endResponse) filterContext.HttpContext.Response.RedirectToAction(action, controller, routeValues, true);
else filterContext.Result = new RedirectToRouteResult(CreateRoute(action, controller, routeValues));
}
public static void RedirectToAction(this ExceptionContext filterContext, String action, String controller, object routeValues = null, bool endResponse = false)
{
if (endResponse) filterContext.HttpContext.Response.RedirectToAction(action, controller, routeValues, true);
else {
filterContext.ExceptionHandled = true;
filterContext.Result = new RedirectToRouteResult(CreateRoute(action, controller, routeValues));
}
}
public static RouteValueDictionary CreateRoute(String action, String controller, object routeValues = null)
{
RouteValueDictionary result = routeValues != null ?
HtmlHelper.AnonymousObjectToHtmlAttributes(routeValues) :
new RouteValueDictionary();
result["controller"] = controller;
result["action"] = action;
return result;
}
}
还有更多的ControllerContext未包括在内,但是根据需要添加自己的控制器应该很容易。
OnException
只要您进行设置,您也可以将此代码放入方法中filterContext.ExceptionHandled = true;