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>