I'm trying to access the session state in my global.asax for every request (page, documents, PDF, etc.). I know i can't do that in Application_BeginRequest, and i thought i could in Application_AcquireRequestState, but it won't works, which is strange because it works in another project.
So, i'm looking for an event in which i would always have access to the session state for every request.
Thanks
EDIT: @Mike
I tried doing this
Sub Application_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As EventArgs)
Session("test") = "test"
End Sub
But i still get errors as i don't have access to session state.
The session gets loaded during Application_AcquireRequestState. Your safe bet is to build Application_PreRequestHandlerExecute
and access it there.
Update: Not every request has a session state. You need to also check for null: if (System.Web.HttpContext.Current.Session != null)
.
The initial Request
will not have a Session
tied to it. Thus, you need to check if Session
is not null
:
var session = HttpContext.Current.Session;
if(session != null) {
/* ... do stuff ... */
}
Based on the input of Mike, here is a snippet with my working code in Global.asax:
namespace WebApplication
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
/* ... */
}
protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
if (HttpContext.Current.Session != null && HttpContext.Current.Session["isLogged"] != null && (bool)HttpContext.Current.Session["isLogged"])
{
HttpContext.Current.User = (LoginModel)HttpContext.Current.Session["LoginModel"];
}
}
}
}
And in the controller:
namespace WebApplication.Controllers
{
[Authorize]
public class AccountController : Controller
{
/* ... */
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Don't do this in production!
if (model.Username == "me") {
this.Session["isLogged"] = true;
this.Session["LoginModel"] = model;
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With