I have tried in Global.asax.cs
protected void Application_BeginRequest(object sender, EventArgs e)
{
try
{
var cookiesDataUserinfo = HttpContext.Current.Request.Cookies["UserInfo"];
if (cookiesDataUserinfo != null)
{
Session["UserId"] = cookiesDataUserinfo["UserId"].ToString();
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
But I am getting the error "Session state is not available in this context." I also tried to load data from cookies in constructor of a controller. But cookies is null inside constructor. Is there any way where I can set session values from cookies before any view is rendered in my MVC project?
CodePudding user response:
I have found the solution I was looking for. I need to use the Application_AcquireRequestState
method in Global.asax.cs
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
try
{
var cookiesDataUserinfo = HttpContext.Current.Request.Cookies["UserInfo"];
if (cookiesDataUserinfo != null)
{
Session["UserId"] = cookiesDataUserinfo["UserId"].ToString();
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
For every request the Application_AcquireRequestState
method is called and I can set session values from Cookies if available.