0

I am using .net framework 4.5 and following is the sample asp.net application code to get the session from HttpConttext.Current but HttpConttext.Current always return null. Earlier I was using .net framework version 4.0 but when I google this issue I found some link that suggested to change the .net framework version from 4.0 to 4.5 to fix this issue but it still does not working.

I used this app setting as well but no luck

   <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />

Code Behind

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["UserName"] = "neeraj";
    }
    protected void btnGetHttpContext_Click(object sender, EventArgs e)
    {
        string name = Convert.ToString(HttpContext.Current.Session["UserName"]);
        TestContext t = new TestContext();
        t.GetContext();
    }
}

TestContext.cs

using System;
using System.Threading.Tasks;
using System.Web;

public class TestContext
{

    public void GetContext()
    {
        StartTask();
    }

    public void StartTask()
    {

        var TaskInit = new Task(() =>
        {


        });

        var Task1 = TaskInit.ContinueWith(a =>
        {
            Task2();
        });

        TaskInit.Start();

    }

    private void Task1()
    {

    }

    private void Task2()
    {
        string s = Convert.ToString(HttpContext.Current.Session["UserName"]);  //HttpContext.Current always return null
    }

}

Web.config

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>

  <system.web>
    <httpRuntime targetFramework="4.5"/>
    <compilation debug="true"/>
  </system.web>
</configuration>
Neeraj Kumar Gupta
  • 2,157
  • 7
  • 30
  • 58
  • Possible duplicate of [Access HttpContext.Current from different threads](https://stackoverflow.com/questions/8925227/access-httpcontext-current-from-different-threads) – pmcilreavy Jan 02 '18 at 10:29
  • @pmcilreavy, I checked that link but it suggests to pass the HttpCntext to your class manually, but that does not solve my problem as I am storing the session in SQL server and even if I pass the HttpCntext, I am unable to get the session data, this is why I used the .framework version to 4.5 as suggested in link http://bartwullems.blogspot.in/2013/09/aspnet-web-api-httpcontextcurrent-is.html – Neeraj Kumar Gupta Jan 02 '18 at 10:46

0 Answers0