C# Cannot check Session exists?

前端 未结 8 2007
遥遥无期
遥遥无期 2020-12-14 20:26

I get an error when I do the following:

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

The error i get is this:

Object reference not

8条回答
  •  独厮守ぢ
    2020-12-14 20:53

    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
        }
    }
    

提交回复
热议问题