小编典典

路由请求时HttpContext.Current.Session为null

c#

没有路由,HttpContext.Current.Session有没有,所以我知道它StateServer正在工作。当我的路线我的要求,HttpContext.Current.Sessionnull在路由页面。我在IIS
7.0上使用.NET 3.5
sp1,但没有MVC预览。似乎AcquireRequestState在使用路由时永远不会触发,因此不会实例化/填充会话变量。

当我尝试访问Session变量时,出现以下错误:

base {System.Runtime.InteropServices.ExternalException} = {"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 <configuration>.

在进行调试时,我还收到了HttpContext.Current.Session在该上下文中不可访问的错误。

-

我的web.config样子是这样的:

<configuration>
  ...
  <system.web>
    <pages enableSessionState="true">
      <controls>
        ...
      </controls>
    </pages>
    ...
  </system.web>
  <sessionState cookieless="AutoDetect" mode="StateServer" timeout="22" />
  ...
</configuration>

这是IRouteHandler的实现:

public class WebPageRouteHandler : IRouteHandler, IRequiresSessionState
{
    public string m_VirtualPath { get; private set; }
    public bool m_CheckPhysicalUrlAccess { get; set; }

    public WebPageRouteHandler(string virtualPath) : this(virtualPath, false)
    {
    }
    public WebPageRouteHandler(string virtualPath, bool checkPhysicalUrlAccess)
    {
        m_VirtualPath = virtualPath;
        m_CheckPhysicalUrlAccess = checkPhysicalUrlAccess;
    }

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        if (m_CheckPhysicalUrlAccess
            && !UrlAuthorizationModule.CheckUrlAccessForPrincipal(
                   m_VirtualPath,
                   requestContext.HttpContext.User,
                   requestContext.HttpContext.Request.HttpMethod))
        {
            throw new SecurityException();
        }

        string var = String.Empty;
        foreach (var value in requestContext.RouteData.Values)
        {
            requestContext.HttpContext.Items[value.Key] = value.Value;
        }

        Page page = BuildManager.CreateInstanceFromVirtualPath(
                        m_VirtualPath, 
                        typeof(Page)) as Page;// IHttpHandler;

        if (page != null)
        {
            return page;
        }
        return page;
    }
}

我也尝试过将EnableSessionState="True"aspx页面放在顶部,但是什么也没做。

有什么见解吗?我应该编写另一个HttpRequestHandler实现的工具IRequiresSessionState吗?

谢谢。


阅读 424

收藏
2020-05-19

共1个答案

小编典典

得到它了。实际上,这很愚蠢。在我删除并添加SessionStateModule后,它的工作原理如下:

<configuration>
  ...
  <system.webServer>
    ...
    <modules>
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      ...
    </modules>
  </system.webServer>
</configuration>

仅仅添加它是行不通的,因为“会话”应该已经在中定义了machine.config

现在,我想知道这是否是平常的事情。由于它看起来如此粗略,因此肯定不会如此……

2020-05-19