user1882705
user1882705

Reputation: 1081

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

Upvotes: 11

Views: 19377

Answers (2)

Harshal Bulsara
Harshal Bulsara

Reputation: 8254

The accepted answer actually does not redirect to the page specified at HandleUnauthorizedRequest time.

I had to modify few things to make it work

public class SessionAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return httpContext.Session["InsuredKey"] != null;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
                              new RouteValueDictionary
                              {
                                   { "action", "YourAction" },
                                   { "controller", "YourController" }
                              });
    }
}

It might be helpful for future users.

Upvotes: 11

Sergey Litvinov
Sergey Litvinov

Reputation: 7458

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
{
}

Upvotes: 16

Related Questions