Thursday, 4 July 2013

How to Check session value before the action gets executed

Step:1
 First of all create a class named pageFilter in your solution and write following code.

public class PageFilter : ActionFilterAttribute
   {
       public override void OnActionExecuting(ActionExecutingContext filterContext)
       {
           HttpContext ctx = HttpContext.Current;

               // If the browser session has expired...
               if (ctx.Session["UserName"] == null)
               {
                   if (filterContext.HttpContext.Request.IsAjaxRequest())
                   {
                       filterContext.Result = new JsonResult { Data = "_Logon_" };
                   }
                   else
                   {
                       filterContext.Result = new RedirectToRouteResult(
                           new RouteValueDictionary {
                               { "Controller", "Demo" },
                               { "Action", "Login" }
                       });
                   }
               }
       }
}

Step-2
Then add [PageFilter] attribute to your controller class .

Example:-
[PageFilter]
public class DemoController : Controller
{
}

No comments:

Post a Comment