Session State Behavior Per Action in ASP.NET MVC

Introduction

The SessionState Attribute helps us to controll the session state behavior in ASP.NET MVC. We can make session state disable / read only / required for controller using this attribute. This is a class level attribute so we can only apply this attribute at the controller level. Some of the action methods of a controller might have a different behavior than the controller session state behavior. In this case the following solution is very useful. So we can apply a session state behavior per action in ASP.NET MVC.

Problem Statement

We can control session state behavior using SessionState attribute but this can only be applied at the controller level. This means that all action methods of the controller have the same session state behavior. Now if some of the action methods of the controller do not use a session and some of action method does use the session then what is the solution?

Solution

In this scenario, we can create a different controller and move all the action methods that have the same session state behavior for in the same controller class. This is not a good solution. Instead of doing this we can create a custom action attribute that overwrites the behavior of the session state for the specific action method.

Use the following procedure to create a custom action attribute that overrides the behavior of the session state.

Step 1: Create custom attribute

  1. [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]  
  2. public sealed class ActionSessionStateAttribute : Attribute  
  3. {  
  4.     public SessionStateBehavior Behavior { getprivate set; }   
  5.     public ActionSessionStateAttribute(SessionStateBehavior behavior)  
  6.     {  
  7.         this.Behavior = behavior;  
  8.     }  
  9. } 

 

Step 2: Create custom controller factory

  1. public class CustomControllerFactory : DefaultControllerFactory  
  2. {  
  3.     protected override SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, Type controllerType)  
  4.     {  
  5.         if (controllerType == null)  
  6.         {  
  7.             return SessionStateBehavior.Default;  
  8.         }  
  9.         var actionName = requestContext.RouteData.Values["action"].ToString();  
  10.         MethodInfo actionMethodInfo;  
  11.         actionMethodInfo = controllerType.GetMethod(actionName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);  
  12.         if (actionMethodInfo != null)  
  13.         {  
  14.             var actionSessionStateAttr = actionMethodInfo.GetCustomAttributes(typeof(ActionSessionStateAttribute), false)  
  15.                                 .OfType<ActionSessionStateAttribute>()  
  16.                                 .FirstOrDefault();  
  17.    
  18.             if (actionSessionStateAttr != null)  
  19.             {  
  20.                 return actionSessionStateAttr.Behavior;  
  21.             }  
  22.         }  
  23.         return base.GetControllerSessionBehavior(requestContext, controllerType);  
  24.     }  
  25. }  

Step 3: Register custom controller factory in Global.asax

  1. protected void Application_Start()  
  2. {  
  3.     AreaRegistration.RegisterAllAreas();  
  4.     RegisterGlobalFilters(GlobalFilters.Filters);  
  5.     RegisterRoutes(RouteTable.Routes);  
  6.     ControllerBuilder.Current.SetControllerFactory(typeof(CustomControllerFactory));  
  7. }

Step 4: Attribute usages

  1. [SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)]    
  2. public class HomeController : Controller    
  3. {    
  4.     public ActionResult Index()    
  5.     {    
  6.         ViewBag.Message = "Welcome to ASP.NET MVC!";    
  7.         TempData["test"] = "session less controller test";    
  8.         return View();    
  9.     }  
  10.     [ActionSessionState(System.Web.SessionState.SessionStateBehavior.Required)]    
  11.     public ActionResult About()    
  12.     {    
  13.         Session["test"] = "session less controller test";    
  14.         return View();    
  15.     }    
  16. } 

The following is the output when the “Index” action method is called:

action method

The following is the output when the “About” is called:
 
About action method

Conclusion

We can use the ActionSessionStateAttribute in combination with the controller level attribute SessionStateAttribute, in this case use the ActionSessionStateAttribute overwrite controller attribute on the actions to which it applies. 


Similar Articles