asp.net-mvcsessionsession-stateasp.net-session

Managing Session Variable in View Page After Session Expire


I have to manage a session variable in the view page after session expire In controller

public ActionResult See()
{
   Session["Name"] = "Mani";
   return View();
}

In view

@if(Session["Name"] != null)
{
    Session["Name"]
}

I works fine until Session Expire. But when session expires it shows error

An exception of type 'System.NullReferenceException' occurred in Inex.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

How to logout the user when the session expires.


Solution

  • use a try catch and redirect back to login page in catch ... this is also a good way to check for null exceptions..

    In your View

    @try{
           <p>@Session["Name"].ToString()</p>
    }
    catch(Exception)
    {
    
    }
    

    No need to check with an if else .. also when an exception occurs it will go to catch and application will continue without breaking if any redirect is not made .. if you feel session is expired redirect the user to the login page ..