Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global.asax event that has access to session state

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.

like image 428
Shadowxvii Avatar asked Mar 27 '12 20:03

Shadowxvii


3 Answers

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).

like image 123
Mike Avatar answered Nov 12 '22 12:11

Mike


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 ... */
}
like image 43
Alex Avatar answered Nov 12 '22 14:11

Alex


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;
            }
        }
    }
}
like image 44
Damian Vogel Avatar answered Nov 12 '22 12:11

Damian Vogel