Lok*_*oki 46 c# asp.net routing session-variables
如果没有路由,HttpContext.Current.Session
那么我知道它StateServer
正在运行.当我路由我的请求时,HttpContext.Current.Session
是null
在路由页面中.我在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>
Run Code Online (Sandbox Code Playgroud)
这是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;
}
}
Run Code Online (Sandbox Code Playgroud)
我也试图把它EnableSessionState="True"
放在aspx页面的顶部,但仍然没有.
任何见解?我应该写另一个HttpRequestHandler
实现的IRequiresSessionState
吗?
谢谢.
Lok*_*oki 53
得到它了.实际上相当愚蠢.我删除并添加了SessionStateModule之后就可以了:
<configuration>
...
<system.webServer>
...
<modules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
...
</modules>
</system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)
简单地添加它将不起作用,因为"会话"应该已经在中定义machine.config
.
现在,我想知道这是否是通常的事情.它肯定似乎不是这样,因为它看起来如此粗糙......
gan*_*tas 24
只需在web.config中添加属性runAllManagedModulesForAllRequests="true"
即可system.webServer\modules
.
默认情况下,此属性在MVC和动态数据项目中启用.
小智 15
runAllManagedModulesForAllRequests=true
实际上是一个真正的坏解决方案 这使我的应用程序的加载时间增加了200%.更好的解决方案是手动删除和添加会话对象,并避免一起运行所有托管模块属性.
这些解决方案都不适合我。我添加了以下方法,global.asax.cs
然后Session不为空:
protected void Application_PostAuthorizeRequest()
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
Run Code Online (Sandbox Code Playgroud)