RedirectToAction in ActionFilterAttribute

Last post 04-02-2008 12:12 PM by SteveSanderson. 12 replies.

Sort Posts:

  • RedirectToAction in ActionFilterAttribute

    03-28-2008, 7:04 AM
    • Member
      318 point Member
    • dimi3
    • Member since 12-13-2007, 5:02 PM
    • Posts 166

    Hi,

    I want to create my own filter that redirects non-logged in users.
    Here is my class:

     

    1    public class LoggedInUserOnly : ActionFilterAttribute
    2 {
    3 public override void OnActionExecuting(FilterExecutingContext filterContext)
    4 {
    5 base.OnActionExecuting(filterContext);
    6 if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
    7 {
    8 //RedirectToAction("Login"); 9 }
    10 }
    11 }
     How can I redirect non-logged in users?
     
  • Re: RedirectToAction in ActionFilterAttribute

    03-28-2008, 8:33 AM
    • Member
      638 point Member
    • jbardrof
    • Member since 03-22-2007, 11:47 PM
    • Naples FL
    • Posts 192

    Funny you should mention that!

    http://forums.asp.net/t/1234929.aspx

    As was pointed out in this previous thread, this is exactly the kind of feedback the development team is looking for. 

    In the meantime you could use reflection to "hack" your way into using the RedirectToAction.
     

    Remember if you have gotten your answer to mark your thread as answered.
  • Re: RedirectToAction in ActionFilterAttribute

    03-28-2008, 8:34 AM
    • Contributor
      3,799 point Contributor
    • tgmdbm
    • Member since 12-17-2007, 2:08 PM
    • Posts 816
    • ASPInsiders

    if( filterContext.Controller is MyController )
        (filterContext.Controller as MyController).RedirectToAction("Login");

     

    public class MyController : Controller {
        public new RedirectToAction(RouteValueDictionary values) { base.RedirectToAction( value ); }
    }

     

    Now you just have to make all your controllers inherit from MyController. 

     

    It's not ideal by any means. But it works. you could get the url from RouteTable.Routes.GetVirtualPath and call Response.Redirect yourself. but that's a mess as well.

     

     

  • Re: RedirectToAction in ActionFilterAttribute

    03-28-2008, 8:35 AM
    • Contributor
      3,799 point Contributor
    • tgmdbm
    • Member since 12-17-2007, 2:08 PM
    • Posts 816
    • ASPInsiders

    ... or reflection ;)

  • Re: RedirectToAction in ActionFilterAttribute

    03-28-2008, 8:36 AM
    • Member
      638 point Member
    • jbardrof
    • Member since 03-22-2007, 11:47 PM
    • Naples FL
    • Posts 192

    Heh,

    neither of which are really ideal, I'm still hoping they'll make RedirectToAction and RenderView public in the next preview.
     

    Remember if you have gotten your answer to mark your thread as answered.
  • Re: RedirectToAction in ActionFilterAttribute

    03-28-2008, 8:52 AM
    Answer
    • Member
      318 point Member
    • dimi3
    • Member since 12-13-2007, 5:02 PM
    • Posts 166

    Thank you for your answers.
    For the moment, I will keep my also not ideal solution, which consist of this method (in the controller class itself):

      

    1    [NonAction]
    2    private void RedirectUserIfNotLoggedIn()
    3    {
    4        if (!HttpContext.User.Identity.IsAuthenticated)
    5        {
    6            RedirectToAction("Login");
    7        }
    8    }
    
     
  • Re: RedirectToAction in ActionFilterAttribute

    03-28-2008, 11:53 AM
    • Member
      10 point Member
    • tumickey
    • Member since 11-25-2007, 10:12 AM
    • Viet Nam
    • Posts 9

     public class LoginActionFilterAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(FilterExecutingContext filterContext)
            {
               HttpSessionStateBase session = filterContext.HttpContext.Session;
               Controller control = filterContext.Controller as Controller;
          
             
                if (control != null)
                {
                    if (session["Login"] == null)
                    {
                        filterContext.Cancel = true;
                        control.HttpContext.Response.Redirect("./Login");

                    }
                }
                base.OnActionExecuting(filterContext);
            }
        }

  • Re: RedirectToAction in ActionFilterAttribute

    03-28-2008, 12:01 PM
    Answer

    But what if your controller isn't actually derived from System.Web.Mvc.Controller? This code will work either way:

      

    public class MyFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(FilterExecutingContext filterContext)
        {
            RedirectToRoute(filterContext, 
                new { controller = "SomeController", action = "SomeAction" }
            );
        }
    
        private void RedirectToRoute(FilterContext context, object routeValues)
        {
            var rc = new RequestContext(context.HttpContext, context.RouteData);
            string url = RouteTable.Routes.GetVirtualPath(rc, 
                new RouteValueDictionary(routeValues)).VirtualPath;
            context.HttpContext.Response.Redirect(url, true);
        }
    }
     
  • Re: RedirectToAction in ActionFilterAttribute

    03-28-2008, 12:17 PM
    • Member
      10 point Member
    • tumickey
    • Member since 11-25-2007, 10:12 AM
    • Viet Nam
    • Posts 9

    uhm ,that is great!

      Thanks . 

  • Re: RedirectToAction in ActionFilterAttribute

    03-28-2008, 12:51 PM
    Answer
    • Star
      11,233 point Star
    • nberardi
    • Member since 06-14-2002, 4:58 AM
    • Phoenixville, PA
    • Posts 2,352

    Hi guys,

    I actually took the easy way out and just created an extension method.

     

    1    		/// <summary>
    2    		/// Redirects to action.
    3    		/// </summary>
    4    		/// <param name="filterContext">The filter context.</param>
    5    		/// <param name="responseCode">The response code.</param>
    6    		/// <param name="actionName">Name of the action.</param>
    7    		public static void RedirectToAction(this ControllerContext filterContext, string actionName)
    8    		{
    9    			if (String.IsNullOrEmpty(actionName))
    10   				throw new ArgumentNullException("actionName");
    11   
    12   			RouteValueDictionary values = new RouteValueDictionary();
    13   			values.Add("action", actionName);
    14   
    15   			RedirectToAction(filterContext, values);
    16   		}
    17   
    18   		/// <summary>
    19   		/// Redirects to action.
    20   		/// </summary>
    21   		/// <param name="filterContext">The filter context.</param>
    22   		/// <param name="responseCode">The response code.</param>
    23   		/// <param name="actionName">Name of the action.</param>
    24   		/// <param name="controllerName">Name of the controller.</param>
    25   		public static void RedirectToAction(this ControllerContext filterContext, string actionName, string controllerName)
    26   		{
    27   			if (String.IsNullOrEmpty(actionName))
    28   				throw new ArgumentNullException("actionName");
    29   
    30   			if (String.IsNullOrEmpty(controllerName))
    31   				throw new ArgumentNullException("controllerName");
    32   
    33   			RouteValueDictionary values = new RouteValueDictionary();
    34   			values.Add("action", actionName);
    35   			values.Add("controller", controllerName);
    36   
    37   			RedirectToAction(filterContext, values);
    38   		}
    39   
    40   		/// <summary>
    41   		/// Redirects to action.
    42   		/// </summary>
    43   		/// <param name="filterContext">The filter context.</param>
    44   		/// <param name="responseCode">The response code.</param>
    45   		/// <param name="values">The values.</param>
    46   		public static void RedirectToAction(this ControllerContext filterContext, RouteValueDictionary values)
    47   		{
    48   			VirtualPathData virtualPath = RouteTable.Routes.GetVirtualPath(filterContext, values);
    49   
    50   			string url = null;
    51   			if (virtualPath != null)
    52   				url = virtualPath.VirtualPath;
    53   
    54   			filterContext.HttpContext.Response.Redirect(url);
    55   		}
    
      
    View My Blog Download My URL Rewriter and Reverse Proxy

    Only $9.95/month, ASP.NET, 2GB & SQL 2005
  • Re: RedirectToAction in ActionFilterAttribute

    04-01-2008, 7:04 PM
    • Member
      103 point Member
    • ironside14
    • Member since 01-02-2008, 3:45 PM
    • Issaquah
    • Posts 56

    Good workaround Steve!

  • Re: RedirectToAction in ActionFilterAttribute

    04-02-2008, 8:20 AM
    • Member
      368 point Member
    • maartenba
    • Member since 01-23-2008, 1:27 PM
    • Belgium
    • Posts 76

    Another alternative to redirecting to login page:

                    string redirectUrl = string.Format(
                        "{0}?returnUrl={1}",
                        FormsAuthentication.LoginUrl,
                        filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.AbsolutePath)
                    );
                    filterContext.HttpContext.Response.Redirect(redirectUrl, true);

    Using this approach, you can specify the login url in your web.config <authentication><forms> configuration.

    Visit my blog at http://blog.maartenballiauw.be

    Order my book ASP.NET MVC 1.0 Quickly via http://www.packtpub.com/asp-net-model-view-controller-1-0-quickly/book
  • Re: RedirectToAction in ActionFilterAttribute

    04-02-2008, 12:12 PM

    Or, if that's what you want to do, you can replace it with a single line:

    FormsAuthentication.RedirectToLoginPage();

     

Page 1 of 1 (13 items)