简体   繁体   中英

IIS8 MVC asp.NET Session not working. Getting null object reference error

Can't get session variables working, I've tried all the solutions I could find online.

On page 1, I call the following in the c# model

HttpContext.Current.Session["lol1"] = "123";

Later on I use an ajax call to return this session variable to me in the c# model,

return HttpContext.Current.Session["lol1"].ToString();

In javascript, I pick it up in the ajax success function and put it in an alert box with alert(e);

I get an null object reference error. Seems like my variable didn't save into the session. This all works fine on localhost via debug, including the alert.

Things I have tried (currently set):

-DefaultAppPool setting Maximum Worker Processes: 1

-IIS manager->ASP->Services->Session Properties->Enable Session State:true

-IIS manager->Session State->In process

-In my solution web.config:

<system.web>
    <sessionState mode="InProc" timeout="25"></sessionState>
</system.web>

<system.webServer>
    <modules>
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
    </modules>
</system.webServer>

Try setting the SessionStateBehavior in your controller. For example:

[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]

It is recommended to use ReadOnly if you only need to read from Session and not write to it to prevent blocking.

Link to Microsoft's SessionStateBehavior enumeration .

(for more info on ASP.NET's blocking when controllers use writable sessions see this link: Does Session State read/write everything when you access with DynamoDB )

Hope this helps!

Regards,

Ross

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM