views:

584

answers:

2

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

public class IsGuestAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!Ctx.User.IsGuest) filterContext.Result = (filterContext.Controller as Controller).RedirectToAction("Index", "Home");
    }
}

Something that could make it worked?

+2  A: 

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.

veggerby
+3  A: 

Here's a code example:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{

    if (!Ctx.User.IsGuest)
    {
        RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
        redirectTargetDictionary.Add("action", "Index");
        redirectTargetDictionary.Add("controller", "Home");

        filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
    }
}
StuperUser
Or just `new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, {"action", "HomePage" } })`
Domenic