asp.net 删除文件夹导致session失效 解决办法

来源:互联网 发布:java建站 编辑:程序博客网 时间:2024/05/16 10:09
解决方案 

幸运的是,我们有了Reflection and HttpModules的解决方案。 首先创建一个像.cs文件... 
复制代码代码如下:

using System.Reflection; 
using System.Web; 
namespace MyWebsite 

/// <summary> 
/// Stops the ASP.NET AppDomain being restarted (which clears 
/// Session state, Cache etc.) whenever a folder is deleted. 
/// </summary> 
public class StopAppDomainRestartOnFolderDeleteModule : IHttpModule 

public void Init(HttpApplication context) 

PropertyInfo p = typeof(HttpRuntime).GetProperty("FileChangesMonitor", 
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); 
object o = p.GetValue(null, null); 
FieldInfo f = o.GetType().GetField("_dirMonSubdirs", 
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase); 
object monitor = f.GetValue(o); 
MethodInfo m = monitor.GetType().GetMethod("StopMonitoring", 
BindingFlags.Instance | BindingFlags.NonPublic); 
m.Invoke(monitor, new object[] { }); 

public void Dispose() { } 



如果您喜欢在 Application_Start使用Global.asax文件中,放置在Init()代码在Application_Start 中。 我相信在Global.asax使用方法已过时,在使用HttpModules可以响应网络(应用程序生命周期的会话开始,会话结束时,)。 init方法在Global.asax同Application_Start作用是一样的,Dipose类似于Application_End。 

我们要以上述代码起作用,需要在web.config文件<httpModules>区段中放入: 

<add name="stopAppDomainRestartOnFolderDelete" 
type="MyWebsite.StopAppDomainRestartOnFolderDeleteModule" /> 
需要说明的是,"stopAppDomainRestartOnFolderDelete"为自定义的任意名称,"MyWebsite"为上述.cs文件中的命名空间,一般为项目名称."StopAppDomainRestartOnFolderDeleteModule"为上述.cs文件中的类名. 

这就是它。 这将防止文件夹删除AppDomain重新启动,但修改web.config和bin文件夹时仍会重新启动,这正是我们想要的。 

但是多删除几个文件就会发现session还是会过期,为什么会是这样的呢?现在还没搞清楚...于是在网上搜索就有了下面的这种方式 

在 <system.web>下面配置session的保存方式为stateserver就可以了 

<sessionState mode="StateServer" stateNetworkTimeout="20" 
stateConnectionString="tcpip=127.0.0.1:42424" />