Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check session variable existence in MVC before we do any activity on page?

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

like image 892
user1882705 Avatar asked Dec 26 '13 16:12

user1882705


People also ask

How do I check if a session variable exists?

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.

Where the session value is stored in MVC?

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.

How do you check if session is expired in MVC?

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.


1 Answers

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
{
}
like image 137
Sergey Litvinov Avatar answered Nov 16 '22 01:11

Sergey Litvinov