I have a scenario like :
search control where our data entry guys enter user id and search for their details and navigate through different pages related to that user.
So in my MVC application right now i am setting a session to maintain the user id in session variable. And on every method on page (like edit, update ..etc) I am checking if user session exist or not. Can i do it globally so i don't need to check every time? Like in global.asax
protected void Application_Start()
{
}
or write a custom method to check the session.
Please can somebody help me the way to do it.
Thanks
You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable.
It is also a dictionary object and derived from ViewDataDictionary. As Data is stored as Object in ViewData, while retrieving, the data it needs to be Type Casted to its original type as the data is stored as objects and it also requires NULL checks while retrieving.
So, if the session expires in 20 minutes, then it is redirected to login page. In that case, we need to check if session exists (not null) in every action/ every controller which requires authentication. We have to two methods to check. We can check in every ActionResult.
In MVC application you can make own attribute that inherits from AuthorizeAttribute , and then in that attribute you can check your session. And you can place it on needed controllers, or to GlobalFilters collection.
UPDATE1
Here is a sample of such logic
public class SessionAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return httpContext.Session["InsuredKey"] != null;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult("/some/error");
}
}
And then you can place it under needed controllers like
[SessionAuthorize]
public class SomeController
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With