可以访问会话状态的Global.asax事件

时间:2012-03-27 20:23:21

标签: asp.net session-state global-asax

我正在尝试访问global.asax中的每个请求(页面,文档,PDF等)的会话状态。我知道我不能在Application_BeginRequest中这样做,我认为我可以在Application_AcquireRequestState中,但它不会工作,这很奇怪,因为它适用于另一个项目。

所以,我正在寻找一个事件,我总是可以访问每个请求的会话状态。

由于

编辑:@Mike

我试过这个

Sub Application_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As EventArgs)
    Session("test") = "test"
End Sub

但由于我无法访问会话状态,我仍然会收到错误。

4 个答案:

答案 0 :(得分:15)

会话在Application_AcquireRequestState期间加载。您可以安全地建立Application_PreRequestHandlerExecute并在那里访问它。


更新:并非每个请求都有会话状态。您还需要检查null:if (System.Web.HttpContext.Current.Session != null)

答案 1 :(得分:7)

最初的Request不会绑定Session。因此,您需要检查Session是否不是null

var session = HttpContext.Current.Session;

if(session != null) {
    /* ... do stuff ... */
}

答案 2 :(得分:0)

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

答案 3 :(得分:0)

基于inputMike,这是我在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"];
            }
        }
    }
}

在控制器中:

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;
            }
        }
    }
}
相关问题