何时会话状态准备好在asp.net中使用

Abb*_*bas 3 c# asp.net session-state global-asax

我有一个asp.net网站,凡在我检查会话变量中Global.asaxApplication_BeginRequest,但它总是说object reference not set to an instance of an object,我不明白这一点,因为我使用的值之前检查空的条件,但仍引发了上述错误,但是当我在default.aspx Page_Load事件中检查它时,它可以正常工作,没有任何问题.

任何人都可以告诉我这背后的问题,我不应该在里面使用会话变量 Application_BeginRequest

如果是,那么我将如何检查会话值,我想要实现的是,如果用户已登录(如果会话["登录"]不为空意味着用户登录)并且有权访问该页面,然后让他/她把他扔到主页.

这就是我在做的事情.
下面的函数检查用户是否已登录:

public static String LoggedInUser
    {
        get
        {
            if (HttpContext.Current.Session["Login"] == null)
                return String.Empty;
            else
                return HttpContext.Current.Session["Login"].ToString();
        }
        set
        {
            HttpContext.Current.Session["Login"] = value;
        }
    }
Run Code Online (Sandbox Code Playgroud)

下面的函数检查用户是否有权访问该页面:

public static bool IsPageAllowed(String Pagename)
{
    bool _isPageAllowed = false;
    XmlDocument doc = new XmlDocument();
    doc.Load(HttpContext.Current.Server.MapPath("Pagenames.xml"));
    if (LoggedInUser != String.Empty)
    {
        XmlNodeList list = doc.DocumentElement.SelectNodes("/AllPages/Pages[@user='" + GetLoggedInUserRole(Globals.LoggedInUser).ToLower() + "']/Page[contains(text(), '" + Pagename + "')]");
        if (list.Count > 0)
            _isPageAllowed = true;
    }
    return _isPageAllowed;
}
Run Code Online (Sandbox Code Playgroud)

以下功能用于根据Application_BeginRequest用户的权限重定向用户:

if (!Globals.IsPageAllowed(rawUrl.Substring(1, rawUrl.Length - 1)))
        {
            Response.Redirect("default.aspx");
        }
Run Code Online (Sandbox Code Playgroud)

Ale*_*kov 6

会话状态在适当命名的HttpApplication.PostAcquireRequestState期间和之后可用.

在获取与当前请求关联的请求状态(例如,会话状态)时发生.

[MSDN](http://msdn.microsoft.com/en-us/library/bb470252.aspx和其他网站,如ASP.NET应用程序生命周期)上提供了完整的描述事件序列.

以下缩短的事件列表(省略了许多事件,有关详细信息,请参阅MSDN链接):

  • BeginRequest
  • AuthenticateRequest
  • AcquireRequestState
  • PostAcquireRequestState
  • ProcessRequestIHttpAsyncHandler.BeginProcessRequest请求的适当IHttpHandler类的方法(或异步版本).例如,如果请求是针对页面的,则当前页面实例处理该请求.

请注意,会话状态至少无法使用AcquireRequestState(如果SessionStateModule在代码之前设法接收该事件,则可以使用会话状态).Session期间没有办法可用BeginRequest.

请注意,如果您需要身份验证/授权,则应使用显式身份验证事件(当您将auth信息保留在会话状态时,它也不适用于您的情况).