【问题标题】:'session state is not available in this context' when multiple files in request当请求多个文件时,“会话状态在此上下文中不可用”
【发布时间】:2012-02-22 16:51:36
【问题描述】:

http://support.microsoft.com/kb/2527105 的代码示例正是我在两个子域之间共享会话所需要的。唯一的问题是它在现实生活中不起作用。当请求的唯一文件是页面本身时,它工作正常,但当其他文件是请求的一部分时抛出错误“会话状态在此上下文中不可用”,例如如果我将样式表或 javascript 文件添加到页面。代码在下面的“if (context.Session != null &&”行中生成此错误:

void context_PostRequestHandlerExecute(object sender, EventArgs e)
{
    HttpApplication context = (HttpApplication)sender;
    HttpCookie cookie = context.Response.Cookies["ASP.NET_SessionId"];

    if (context.Session != null &&
        !string.IsNullOrEmpty(context.Session.SessionID))
    {
        cookie.Value = context.Session.SessionID;
        if (rootDomain != "localhost")
        {
            cookie.Domain = rootDomain;
        }
        cookie.Path = "/";
    }
}

【问题讨论】:

  • 你应该给它一个描述问题的标题,而不是询问人们是否熟悉这个例子。
  • 好的,编辑了标题,希望能吸引一些熟悉的人。
  • 我稍微调整了一下。
  • 作为一个快速测试,将您的 if 语句包装在以下内容中:if(context.Request.Path.ToUpper().IndexOf(".ASPX") > 0) {} 以查看 if 会发生什么您从此代码中排除任何非 aspx 文件(即,仅当当前请求是针对 aspx 页面而不是 HTML 页面或 CSS 文件等时才继续)。我很惊讶他们被推过处理程序,如果这是问题的话。
  • 如果我把它包裹起来,它确实有效。这些文件被推送到处理程序中,我也有点惊讶。

标签: c# asp.net session httpapplication


【解决方案1】:

你可以尝试一个 Try Catch 块,然后你可以捕获一个空值。

    private HttpSessionState GetSession(HttpApplication context)
    {
        try
        {
            //On Abadon or Logout this returns "Session state is not available in this context. "
            return context.Session;
        }
        catch (HttpException)
        {
            return null;
        }
    }

【讨论】:

    猜你喜欢
    • 2011-10-19
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 2013-10-19
    相关资源
    最近更新 更多