C# Cannot check Session exists?

亡梦爱人 提交于 2019-11-27 13:49:02

问题


I get an error when I do the following:

if(Session["value"] != null)
{
   // code
}

The error i get is this:

Object reference not set to an instance of an object.

Why is this? I always check my session this way? I am using the MVC Framework, does this has something to do with it?

EDIT:

The code is in the constructor of a Controller:

public class MyController : ControllerBase
{
    private int mVar;

    public MyController()
    {
        if (Session["value"] != null)
        {
            mVar= (int)Session["value"];
        }
    }
}

回答1:


The session only really exists during the processing of an action - I wouldn't expect it to be valid in the constructor of a controller. For example, the controller might (for all I know) be re-used between requests.

You will need to do this either in the action (method), or (perhaps more appropriately) in an action filter, or the OnActionExecuting (etc) method(s):

public abstract class ControllerBase : Controller
{
    protected override void OnActionExecuting(
        ActionExecutingContext filterContext)
    {
        // code involving this.Session // edited to simplify
        base.OnActionExecuting(filterContext); // re-added in edit
    }
}



回答2:


The [] is an indexer, it acts like a method on the class.

In this case, Session is null and you cannot perform the indexing on it.

Do this:

if(Session != null && Session["value"] != null)
{
   // code
}



回答3:


You'll have to do it like this-

if(null != HttpContext.Current.Session["Value"])
{
    //Code here.
}



回答4:


You're getting this error because the "Session" object is null. Therefore it's impossible to look at the ["value"] bit of it. I'm not familiar with MVC, but either there's a bigger problem whereby the Session object isn't being created, or you're accessing it at the wrong point of the lifecycle, or you just need a test to check if Session != null.




回答5:


The syntax used by you:

if (Session["mySessionVariable"] != null)
{

}

... is the correct way to check for a Session object in ASP.NET. I suspect that the problem is because you are using ASP.NET MVC.

Maybe some of our MVC experts can enlighten us as to the correct way of doing this in ASP.NET MVC.

Edit: I see that Marc Gravell has posted his answer while I'm typing this. That should be illuminatory.




回答6:


I solve by this way:

if (Session.Count > 0 && Session["mySessionVariable"].ToString() != null)
{

}



回答7:


if(Session != null && Session["name"] != null && Session["name"].ToString()!="")
{
   //fire code
}



回答8:


You also can use:

if (Session == null || String.IsNullOrEmpty((string)Session["session_object"])){
   // Do something
}


来源:https://stackoverflow.com/questions/759795/c-sharp-cannot-check-session-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!