How to check the existence of a session variable in MVC before doing any actions on the page?

I have a script like:

search control, where our data entry users enter a user ID and search for their data and navigate through the various pages associated with that user.

So, in my MVC application, right now I am setting up a session to maintain the user ID in the session variable. And every method on the page (e.g. editing, updating..etc) I check if the user session exists. Can I do this all over the world, so I don’t need to check every time? Like in global.asax

protected void Application_Start() { } 

or write your own session verification method.

Please help me how to do this.

thanks

+7
c # asp.net-mvc session
source share
2 answers

In an MVC application, you can create your own attribute that inherits from AuthorizeAttribute , and then in this attribute you can test your session. And you can place it on the necessary controllers or in the GlobalFilters collection.

Update1

Here is an example 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 the necessary controllers, for example

 [SessionAuthorize] public class SomeController { } 
+11
source share

The accepted answer does not actually redirect the page specified in HandleUnauthorizedRequest .

I had to change a 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" } }); } } 

This may be useful for future users.

+7
source share

All Articles