How to Set and Retrieve Session in ASP.NET MVC 5?

2019-08-16 02:11发布

问题:

I am working on an ASP.NET MVC 5 application and I am having problem storing data to session. The value I get is always null.

Here is where I set the session:

string mail = user.Email;
string response = user.CheckEmail();
Session["email"] = mail;

I am testing the session here, It is redirecting to YYY:

if ((string)Session["mail"] != null)
{
    return RedirectToAction("PPP");
}
else
{
    return RedirectToAction("YYY");
}

Please immediate help will be appreciated. Thanks

回答1:

You have typo.

Session["email"] = mail;

if ((string)Session["mail"] != null)
                    ^^^^

Session name should be email. In addition, you should not cast to string in order to check null.

if (Session["email"] != null)