whats the best way to do a redirect (preferably a redirect to action) from within an ActionFilterAttribute?
I want to be able to pass data into the controller action from within the ActionFilterAttribute as well.
Alternatively to a redirect, if it is calling your own code, you could use this: actionContext. Result = new RedirectToRouteResult( new RouteValueDictionary(new { controller = "Home", action = "Error" }) ); actionContext. Result.
public override void OnActionExecuting(ActionExecutingContext filterContext) { ... if (needToRedirect) { ... filterContext. Result = new RedirectResult(url); return; } ... } Instead of new RedirectResult(url) you could also use new RedirectToAction(string action, string controller) .
RedirectToAction(String, String, RouteValueDictionary) Redirects to the specified action using the action name, controller name, and route values.
By including a NuGet package called MvcContrib you can easily pass model or form data through a simple RedirectToAction function call inside of your controllers.
To redirect, override OnActionExecuting
and assign a new RedirectToRouteResult
to filterContext.Result
:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary { { "action", "newActionName" },
{ "actionArgument", someData } });
}
To assign data when redirecting, put it into the route, as shown above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With