gpt4 book ai didi

asp.net - ASP .NET 检查 session

转载 作者:行者123 更新时间:2023-12-02 13:08:26 25 4
gpt4 key购买 nike

我想在使用它之前检查基页面类中的 Session 是否存在,但我发现如果它不存在,只需检查就会抛出异常:

if (Session != null)
{
Session.Remove("foo");
}

将抛出此异常:

Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the \\ section in the application configuration.

检查发生在我的所有 aspx 页面派生自的基页面类的 Load 事件中。该应用程序已启用 session ,并且具有 httpModules 节点中列出的模块。这是一个经常使用 session 的应用程序,通常没有问题。

我仅在某些页面上收到此错误,并且大多数时候它不可靠。我知道我应该做一些不同的事情来防止错误,但我不确定什么?

我是否在生命周期中过早调用 session ?我是否没有正确检查 session 是否可用?

最佳答案

你可以使用这样的方法来判断当前请求是否使用session:

    public static bool RequestHasSession
{
get
{
return (HttpContext.Current.Handler is IRequiresSessionState);
}
}

如果您不确定自己是否在 Web 上下文中运行,则需要事先检查 HttpContext.Current 是否不为 null。

关于asp.net - ASP .NET 检查 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1125376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com