Monday 30 May 2016

Maintain Session For Login User Using ActionFilter in Asp.Net MVC

Action Filter
Action filters contain logic that is executed before and after a controller action executes.
2methods we can override from the action filter.

1. OnActionExecuting :before execution
2. OnActionExecuted  :After execution

Check session value on Action Filter
1. Create a class (e.g  SessionExpire ) derived from ActionFilterAttribute Class.

public class SessionExpire:ActionFilterAttribute


2. Override the OnActionExecuting method in created class (SessionExpire) .
       public override void OnActionExecuting(ActionExecutingContext filterContext)
{
……….
……….
}

3. In side this method check the session value is available or not, if not available then redirect to login page.


public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if ((HttpContext.Current.Session["UserName"] == null) ||                                                                                
                                 (HttpContext.Current.Session["UserID"]==null))
               {
         filterContext.Result = new RedirectResult("~/Account/Login");
         return;
                      }
4. How to use in Action Method of controller:
We can use this by the class name derived from ActionFilterAttribute in the controller.
 [SessionExpire]
        public ActionResult SubmitTimesheet()
        {
………………..
………………….
 }
These are the simple steps to check session in Action level

Restrict different Users for specific Action Method of  controller
1. If we are Using Roll in Db to restrict different user for different controllers
We have to modify little bit code on that . i.e if a user of contractor want to access a method of admin then it should show you are not authorized for that page

Suppose we have 3 users namely below
User Roll Id User Roll Name
1 Contractor
2 Approver
3 Admin

2. While login we are storing the user type in session as below
      HttpContext.Current.Session["UserType"]=user.userid;
3. To check the action method belongs to particular user type or not we have to pass the user type from action method to SessionExpire  class derived from ActionFilterAttribute Class.
Like:
[SessionExpire(<UserType>)]

[SessionExpire(1)]
        public ActionResult SubmitTimesheet()
        {
………………..
………………….\
Return view();
               }
4. To get the User Type and validate with session value of user Type we have to modify the SessionExpire Class.
    public class SessionExpire:ActionFilterAttribute
    {
 public int sessionid { get; set; }
        public SessionExpire(int roll=999)
        {
            sessionid = roll;
        }
       public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
……….
……….
 }
     }
Note: By default roll is 999 if we are not passing any value from action method if we are passing “1” then roll will be “1” and that will assign to “sessionid” property


5. Below are the code used to check the session value with passed usertype from action method
in OnActionExecuting Method .

public class SessionExpire:ActionFilterAttribute
    {
        public int sessionid { get; set; }

        public SessionExpire(int roll=999)
        {
            sessionid = roll;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
       if ((HttpContext.Current.Session["UserName"] == null) ||
         (HttpContext.Current.Session["UserID"]==null))  (Note:Checking for session exist or not )
                {
                    filterContext.Result = new RedirectResult("~/Account/Login");
                    return;
                }


  if ((int)HttpContext.Current.Session["UserType"] != sessionid)
           (Note: Checking stored session id match to passed usertype id from action )
       {
             if ((int)HttpContext.Current.Session["UserType"] == 1)
      (Note: check with login Usertype and redirect to Unauthorized page of Login User )
                {
                filterContext.Result =
                new RedirectResult("~/Contractor/notauthorised");
                    return;
                }

            if ((int)HttpContext.Current.Session["UserType"] == 2)
                {
                 filterContext.Result = new RedirectResult("~/Approver/notauthorised");
                 return;
                }
            if ((int)HttpContext.Current.Session["UserType"] == 3)
                {
             filterContext.Result = new RedirectResult("~/Admin/notauthorised");
              return;
                }
         }
                base.OnActionExecuting(filterContext);
   }
}






Redirect to Particular page when Session Fails in Action Filter

When we are working in particular page and that time session fails then it will Navigate to login page and after login page it should redirect to That page instead of home page . I did this with Action filter.

1. If session fails Store the Url in a session
2. After signin redirect to session stored Url
As Code
public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
        if ((HttpContext.Current.Session["UserName"] == null) ||                                            
(HttpContext.Current.Session["UserID"]==null))
(Note: Checking for session fails or not  ? if fails then store in a new session variable for redirect after login )
        {              
HttpContext.Current.Session["Urlreturn"] = HttpContext.Current.Request.Url+"";
filterContext.Result = new RedirectResult("~/Account/Login");
return;

        }
 }


In Login action check if data exist in session then rediredct to that page

if ((Session["Urlreturn"] as string) != null)
(Note :checking for stored Url is Exist after login)
                {
                    return Redirect((Session["Urlreturn"] + ""));
(Note: If exist then redirect to Stored URL where session fails)
                }


Thanks,


Pradeep Kumar Das