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"); } }
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.
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.
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.
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.
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" } }); } } }
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