Shadowxvii
Shadowxvii

Reputation: 1120

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.

Upvotes: 12

Views: 17572

Answers (4)

Damian Vogel
Damian Vogel

Reputation: 1182

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;
            }
        }
    }
}

Upvotes: 2

Vin&#237;cius Todesco
Vin&#237;cius Todesco

Reputation: 1897

If HttpContext.Current IsNot Nothing AndAlso HttpContext.Current.Session IsNot Nothing Then
strError = HttpContext.Current.Session("trCustomerEmail")
End If

Upvotes: 0

Mike
Mike

Reputation: 1974

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

Upvotes: 18

Alex
Alex

Reputation: 35407

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 ... */
}

Upvotes: 9

Related Questions