ASP.NET + C# HttpContext.Current.Session is null (

2020-02-22 03:43发布

this is how I initiate the session

 protected void Session_Start(object sender, EventArgs e)
    {
        HttpContext.Current.Session["CustomSessionId"] = Guid.NewGuid();
    }

in my solution under a class library i am triyng to access it and getting null exception:

string sess = HttpContext.Current.Session["CustomSessionId"] ;

this is my config in web.config and app.config (in my library)

    <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  </system.serviceModel>
  <system.web>
      <pages enableSessionState = "true" />
      <httpModules>
        <add type="System.Web.SessionState.SessionStateModule" name="Session"/>
      </httpModules>
      <compilation debug="true" targetFramework="4.0" />
    </system.web>

(app.config)

1条回答
虎瘦雄心在
2楼-- · 2020-02-22 04:12

According to your comments it seems that you are trying to access the session in a web service. Web services are stateless and that's how they should be. If you want to violate this rule and make them stateful you could enable sessions in a classic ASMX web service like this:

[WebMethod(EnableSession = true)]
public void SomeMethod()
{
    ... invoke the method in your class library that uses Session
}

This being said, using HttpContext.Current in a class library is a very practice that should be avoided at all price.

查看更多
登录 后发表回答