Redirecting to specified controller and action in asp.net mvc action filter

后端 未结 3 581
后悔当初
后悔当初 2020-11-29 21:41

I have written an action filter which detects a new session and attempts to redirect the user to a page informing them that this has happened. The only problem is I can not

相关标签:
3条回答
  • 2020-11-29 21:59

    Call RedirectToAction using this overload:

    protected internal RedirectToRouteResult RedirectToAction(
        string actionName,
        RouteValueDictionary routeValues
    )
    

    In Action Filters, the story is a little different. For a good example, see here:

    http://www.dotnetspider.com/resources/29440-ASP-NET-MVC-Action-filters.aspx

    0 讨论(0)
  • 2020-11-29 22:04

    EDIT: The original question was about how to detect session logout, and then automatically redirect to a specified controller and action. The question proved much more useful as it's current form however.


    I ended up using a combination of items to achieve this goal.

    First is the session expire filter found here. Then I wanted someway to specify the controller/action combo to get a redirect URL, which I found plenty of examples of here. In the end I came up with this:

    public class SessionExpireFilterAttribute : ActionFilterAttribute
    {
        public String RedirectController { get; set; }
        public String RedirectAction { get; set; }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;
    
            if (ctx.Session != null)
            {
                if (ctx.Session.IsNewSession)
                {
                    string sessionCookie = ctx.Request.Headers["Cookie"];
                    if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                    {
                        UrlHelper helper = new UrlHelper(filterContext.RequestContext);
                        String url = helper.Action(this.RedirectAction, this.RedirectController);
                        ctx.Response.Redirect(url);
                    }
                }
            }
    
            base.OnActionExecuting(filterContext);
        }
    }
    
    0 讨论(0)
  • 2020-11-29 22:16

    Rather than getting a reference to HttpContent and redirecting directly in the ActionFilter you can set the Result of the filter context to be a RedirectToRouteResult. It's a bit cleaner and better for testing.

    Like this:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(something)
        {
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary {{ "Controller", "YourController" },
                                          { "Action", "YourAction" } });
        }
    
        base.OnActionExecuting(filterContext);
    }
    
    0 讨论(0)
提交回复
热议问题