c# - session 状态何时准备好在 asp.net 中使用

标签 c# asp.net session-state global-asax

我有一个 asp.net 站点,我正在检查 Application_BeginRequestGlobal.asax 中的 session 变量,但它总是说 object reference not set to一个对象的实例,我不明白这一点,因为我在使用该值之前检查了 null 的条件,但它仍然抛出上述错误,但是当我在 default 中检查它时。 aspx Page_Load 事件它可以正常工作,没有任何问题。

谁能告诉我这背后的问题是什么,我不应该在 Application_BeginRequest 中使用 session 变量吗

如果是,那么我将如何检查 session 值,我想要实现的是,如果用户已登录(如果 Session["Login"] 不为空则表示用户已登录)并且有权访问页面,然后让他/她的其他人把他扔到首页。

这就是我正在做的。
下面的函数检查用户是否登录:

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

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

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

下面的函数用于 Application_BeginRequest 以根据用户的权限重定向用户:

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

最佳答案

session 状态在适当命名 HttpApplication.PostAcquireRequestState 期间和之后可用。 .

Occurs when the request state (for example, session state) that is associated with the current request has been obtained.

在 [MSDN]( http://msdn.microsoft.com/en-us/library/bb470252.aspx 和其他网站,例如 ASP.NET Application Life Cycle

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

  • 开始请求
  • AuthenticateRequest
  • 获取请求状态
  • PostAcquireRequestState
  • 请求的适当 IHttpHandler 类的
  • ProcessRequest 方法(或异步版本 IHttpAsyncHandler.BeginProcessRequest)。例如,如果请求是针对页面的,则当前页面实例会处理该请求。

请注意, session 状态至少在 AcquireRequestState 之前不可用(如果 SessionStateModule 在您的代码之前成功接收到该事件,则它可能可用)。在 BeginRequest 期间,Session 不可能可用。

请注意,如果您需要身份验证/授权,则应使用显式身份验证事件(它也不适用于您的情况,因为您将身份验证信息保留在 session 状态中)。

关于c# - session 状态何时准备好在 asp.net 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19474772/

相关文章:

c# - 使用鼠标绘制图像

asp.net - returnUrl 和 IsLocalUrl()

ios - session cookie 在 Android/iOS 设备上持续多长时间?

c# - Winforms 标签文本未完全显示

asp.net scriptbundle 多个包含 vs 单个包含

c# - XML Xpath 表达式

c# - 跨多个应用程序池的 ASP.Net C# 共享 session

删除 WebApplications 上的目录时 ASP.NET 丢失 session 数据

c# - 正则表达式匹配任何单词组合但不匹配单个小数

c# - ValueTuple 对大对象有多好?