请求中的多个文件时,"会话状态在此上下文中不可用"



http://support.microsoft.com/kb/2527105这正是我在两个子域之间共享会话所需要的。唯一的问题是它在现实生活中不起作用。当请求的ony文件是页面本身时,它可以正常工作,但当其他文件是请求的一部分时,例如当我向页面添加样式表或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 = "/";
    }
}

您可以尝试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;
        }
    }

最新更新