Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get filter to redirect to another action?

RedirectToAction is protected, and we can use it only inside actions. But if I want to redirect in a filter?

public class IsGuestAttribute: ActionFilterAttribute {     public override void OnActionExecuting(ActionExecutingContext filterContext)     {         if (!Ctx.User.IsGuest)              filterContext.Result = (filterContext.Controller as Controller)                 .RedirectToAction("Index", "Home");     } } 
like image 444
Igor Golodnitsky Avatar asked Feb 15 '09 15:02

Igor Golodnitsky


People also ask

How do I redirect an action filter?

If you want to use RedirectToAction : You could make a public RedirectToAction method on your controller (preferably on its base controller) that simply calls the protected RedirectToAction from System. Web. Mvc.

How do I redirect to another action?

To redirect the user to another action method from the controller action method, we can use RedirectToAction method. Above action method will simply redirect the user to Create action method.

How do I redirect from one action to another controller?

Show activity on this post. I am using asp.net MVC 3 and this works: return Redirect("/{VIEWPATH}/{ACTIONNAME}"); . Example, return Redirect("/account/NotAuthorized"); where 'account' is your view path and your controller name is AccountController. Hope this helps.

Which ActionResult redirects to another action method?

RedirectToActionResult is an ActionResult that returns a Found (302), Moved Permanently (301), Temporary Redirect (307), or Permanent Redirect (308) response with a Location header. It targets a controller action, taking in action name, controller name, and route value.


1 Answers

RedirectToAction is just a helper method to construct a RedirectToRouteResult(), so what you do is simply create a new RedirectToRouteResult() passing along a RouteValueDictionary() with values for your action.

Complete sample based on code from @Domenic in the comment below:

public class IsGuestAttribute: ActionFilterAttribute {     public override void OnActionExecuting(ActionExecutingContext filterContext)     {         if (!Ctx.User.IsGuest)          {             filterContext.Result = new RedirectToRouteResult(                 new RouteValueDictionary                  {                      { "controller", "Home" },                      { "action", "Index" }                  });         }     } } 
like image 133
veggerby Avatar answered Oct 13 '22 06:10

veggerby