Hello frnd ,
I am writing this blog for a type of problem which we face
during development in mvc-3 or mvc4 .
For a registered user we have to check Session in every action of every controller
,which is very tedious.
Like this ,
If (YourSessionObject
!= null)
{
//your
code goes here.
}
It is very tedious.
So Here is the solution.
You all know about Mvc Attributes. So we can make one attribute
which will check our session object and if found null then return back to login
page.
So the question is where to write this class, The class will
be written in App_Start .
The class should
implement ActionFilterAttribute.
In that class you have
to over ride OnActionExecuting method.
Here is the code below
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext
filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
CurrentCustomer objCurrentCustomer = new CurrentCustomer();
//This is session object
objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
if (objCurrentCustomer == null)
{
// check if a new session id was generated
filterContext.Result = new RedirectResult("~/Users/Login");
// if null then return back to login page .
return;
}
base.OnActionExecuting(filterContext);
}
}
That’s all just include App_Start in controller and just
add [SessionExpireFilter] attribute in your action method.
This will check session in every action .
No comments:
Post a Comment