Thursday, May 2, 2013

Using Action Filters in MVC

Create Simple Action Filters in MVC is relatively easy. Here is one I created ensuring that the user session is a new Session, and redirects the user to a login screen if not. To use in your ActionResult you put it before the function like so 

[ActionFilterName]

  public ActionResult Action(Model model)
        {
         }

Here is the code (you can put in your own class or in it's own namespace or Controller, make sure you reference it from your controller with using syntax:


 public class ActionFilterName : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;

            if (ctx.Session != null)
                if (ctx.Session.IsNewSession)
                {

                    // If it says it is a new session, but an existing cookie exists, then it must
                    // have timed out
                    string sessionCookie = ctx.Request.Headers["Cookie"];
                    if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                        ctx.Response.Redirect("~/Login");
                }
            
            base.OnActionExecuting(filterContext);
        }

    }

No comments:

Post a Comment