Global.asax event that has access to session state

萝らか妹 提交于 2019-11-30 19:04:25

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 ... */
}
If HttpContext.Current IsNot Nothing AndAlso HttpContext.Current.Session IsNot Nothing Then
strError = HttpContext.Current.Session("trCustomerEmail")
End If

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;
            }
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!