MVC Session: mvc session management example

session in mvc, mvc session management, mvc session state best practices, mvc session management example, session management in mvc c#


In this example, showing how to use and validate session (HttpContext.Current.Session) in MVC application. In my earlier article, one of more secured feature to keep up your website healthy cross-site request forgery explained. MVC application has provided us facility to apply filter like
  1.  Authorization 
  2.  Action Filter 
  3.  Result Filter 
  4.  On Error Filter
I am here applying OnActionExecuting filter helps us to manage MVC session management whether session is preserving or not, if session is expired, it will not let you access your authorised area and throw away to login area or someone page. mvc session management example

Add below code in FilterConfig.cs under App_Start folder

This code is written under OnActionExecuting in FilterConfig.cs file
public class UserSessionActionFilter : ActionFilterAttribute, IActionFilter
    public override void OnActionExecuting(ActionExecutingContext filterContextORG)
        HttpContext ctx = HttpContext.Current;
        if (HttpContext.Current.Session["User"] == null)
            /// this handles session when data is requested through Ajax json
            if (filterContextORG.HttpContext.Request.IsAjaxRequest())
                JsonResult result = new JsonResult { Data = "Session Timeout!" };
                filterContextORG.Result = result;
                /// If session is expired then redirected to logout page which further redirect to login page. 
            filterContextORG.Result = new RedirectResult("~/Main/Home/Logout");

In Global.asax Should register FilterConfig.cs

protected void Application_Start()

Checking Session is expired or not

We have to call action attribute [UserSessionActionFilter] in MVC controller to check whether session is preserving or not. If session is expired it will throw to other page.
public ActionResult ContactDetail()
 return View();


This example is showing how to handle session in MVC application. This example helps us to MVC session management example with all required steps.

Suggested Reading


Anjan kant

Outstanding journey in Microsoft Technologies (ASP.Net, C#, SQL Programming, WPF, Silverlight, WCF etc.), client side technologies AngularJS, KnockoutJS, Javascript, Ajax Calls, Json and Hybrid apps etc. I love to devote free time in writing, blogging, social networking and adventurous life

Post A Comment: