Click here to Skip to main content
13,866,422 members
Click here to Skip to main content
Add your own
alternative version


30 bookmarked
Posted 27 Jun 2014
Licenced CPOL

Session in ASP.NET MVC

, 27 Jun 2014
Rate this:
Please Sign up or sign in to vote.
Session in ASP.NET MVC


In web applications, we use sessions to:

  1. Check if the user is logged in or not
  2. Save permission information
  3. Save temporary data

And some time, we may need to use saved session objects frequently. Here, we will try to centralize our session utility in a single base controller, so that we can use the session objects from other controllers with minimum effort.


Before the beginning, we have to consider some things like:

  1. We are going to use a single session for full web project, which is a good practice.
  2. If a controller is session dependent and session is null, we are going to redirect to a login page.
  3. Not all controllers are session dependent, like LogOnController and ErrorController. So if the session is null, it would not redirect to the login page, and would render its default.

Using the Code

Here is the base controller for our application, which deals with the session utilities. TSource is the Model type which we want to save in to the session. Now, we can use it in two ways.

  1. If the controller is not session dependent, we simply avoid the inheritance.
  2. If the controller is not session dependent, but we are inheriting from the base controller.

Then IsNonsessionController methods nonsessionedController list is important, where we have to specify the names of which controller does not depend on sessions:

public class ApplicationController<TSource> : Controller
    private const string LogOnSession = "LogOnSession";  //session index name
    private const string ErrorController = "Error";      //session independent controller
    private const string LogOnController = "LogOn";      //session independent and LogOn controller    
    private const string LogOnAction = "LogOn";          //action to rederect

    protected ApplicationController()

    protected override void Initialize(RequestContext requestContext)
        /*important to check both, because logOn and error Controller should be access able with out any session*/
        if (!IsNonSessionController(requestContext) && !HasSession())
            //Rederect to logon action
            Rederect(requestContext, Url.Action(LogOnAction, LogOnController)); 

    private bool IsNonSessionController(RequestContext requestContext)
        var currentController = requestContext.RouteData.Values["controller"].ToString().ToLower();
        var nonSessionedController = new List<string>() {ErrorController.ToLower(), LogOnController.ToLower()};
        return nonSessionedController.Contains(currentController);

    private void Rederect(RequestContext requestContext, string action)

    protected bool HasSession()
        return Session[LogOnSession] != null;

    protected TSource GetLogOnSessionModel()
        return (TSource)this.Session[LogOnSession];

    protected void SetLogOnSessionModel(TSource model)
        Session[LogOnSession] = model;

    protected void AbandonSession()
        if (HasSession())

Here LogOnModel is the model which object can be set in to session. And in every controller, we are going to use the base controller like if the controller wants to deal with session.

public class LogOnController : ApplicationController<LogOnModel>

To set session, or to destroy it on logout, or to get the session from any sub controller, we have to use it like:

/*Set model to session*/
LogOnModel model = new LogOnModel();

/*destroy current session*/

/*Shows the session*/
LogOnModel sessionModel = GetLogOnSessionModel();


Here, we have worked with single session only. But your application may need to deal with multiple sessions. To do so, we have to make some changes here. If you need anything like this, just knock me, I already made one to serve such a purpose. If I have time, I will post it within a week.

Find the project attachment, which is a VS 2010 solution and contains MVC3 project.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Bangladesh Bangladesh
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Rubaiyat Hasan24-Jul-18 0:34
memberRubaiyat Hasan24-Jul-18 0:34 
QuestionWorking Code Pin
Member 1168965716-Apr-16 11:32
memberMember 1168965716-Apr-16 11:32 
QuestionQuestion - Issue Pin
Gsanbrook8-Jun-15 9:22
memberGsanbrook8-Jun-15 9:22 
AnswerRe: Question - Issue Pin
DiponRoy12-Jun-15 13:00
memberDiponRoy12-Jun-15 13:00 
QuestionThanks Pin
Gsanbrook28-May-15 9:06
memberGsanbrook28-May-15 9:06 
AnswerRe: Thanks Pin
DiponRoy28-May-15 9:31
memberDiponRoy28-May-15 9:31 
QuestionRequest Multi Session Logic Pin
kahn.fahd15-Apr-15 5:54
memberkahn.fahd15-Apr-15 5:54 
Questionmultiple sessions Pin
sgeorge10611-Mar-15 8:32
membersgeorge10611-Mar-15 8:32 
AnswerRe: multiple sessions Pin
DiponRoy11-Mar-15 11:02
memberDiponRoy11-Mar-15 11:02 
QuestionAbout Multiple sessions.. Pin
BALAG BE22-Jan-15 0:38
memberBALAG BE22-Jan-15 0:38 
AnswerRe: About Multiple sessions.. Pin
DiponRoy23-Jan-15 11:26
memberDiponRoy23-Jan-15 11:26 
QuestionVerification Pin
philals8-Sep-14 14:07
memberphilals8-Sep-14 14:07 
AnswerRe: Verification Pin
DiponRoy9-Sep-14 1:00
memberDiponRoy9-Sep-14 1:00 
GeneralMy vote of 2 Pin
Samer Abu Rabie28-Jun-14 11:28
memberSamer Abu Rabie28-Jun-14 11:28 
GeneralRe: My vote of 2 Pin
DiponRoy28-Jun-14 22:16
memberDiponRoy28-Jun-14 22:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190214.1 | Last Updated 27 Jun 2014
Article Copyright 2014 by DiponRoy
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid