關于session失效這個問題看似簡單,如果搞不好會非常坑爹的,下面就詳細說說設定session失效時間的辦法。
一、伺服器設定session
IIS-網站-屬性-Asp.net-編輯配置-狀态管理-會話逾時(分鐘)-設定為120,即為2小時,即120分鐘後如果目前使用者沒有操作,那麼Session就會自動過期。
二、網站設定session
IIS-網站-具體網站(如DemoSite)-屬性-Asp.net,此時有兩個選項,一個是“編輯全局配置”,一個是“編輯配置”。
如果“編輯全局配置”,就和上個配置一樣。
如果“編輯配置”,則隻對目前網站生效。因為一個伺服器可能有很多獨立網站。
1、繼續選擇“狀态管理”-會話逾時(分鐘)-設定為360,即360分鐘。效果同上,隻不過隻對目前網站生效。
2、身份認證-Forms-Cooke逾時,選擇"12:00:00",即12個小時。可選項共有以下八項:
00:15:00
00:30:00
01:00:00
02:00:00
04:00:00
08:00:00
12:00:00
1:00:00:00
即最長24小時,最小15分鐘。這是預設的配置。在應用中可以自由定制。
三、應用程設定 session
同網站管理,隻不過作用域僅限目前應用程式。
既可以在web.config中設定,也可以在Global.asax設定:
void Session_Start(object sender, EventArgs e)
{
// 在新會話啟動時運作的代碼 600分鐘
Session.Timeout = 600;
}
四、頁面設定session
在某頁面中,設定Session.Timeout = 30;即可臨時修改某頁面的會話過期時間。
檢視某個Session的過期時間
TimeSpan SessTimeOut = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0);
TimeSpan SessTimeOut = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0);
其中,網站和應用程式的設定,展現在Web.config中即:
網站:
<?xml version="1.0"?>
<configuration>
<system.web>
<authentication mode="Forms" >
<forms name="AuthLogin" loginUrl="/Login.aspx" protection="All" timeout="360" slidingExpiration="true"/>
</authentication>
<sessionState mode="InProc" cookieless="false" timeout="20" />
</system.web>
<location path="Login.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
</configuration>
應用程式:
<?xml version="1.0"?>
<configuration>
<system.web>
<authentication mode="Forms" >
<forms name="AuthLogin" loginUrl="/Login.aspx" protection="All" timeout="360" slidingExpiration="true"/>
</authentication>
<sessionState mode="InProc" cookieless="false" timeout="20" />
</system.web>
<location path="Login.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
</configuration>
以上四處設定的優先級為:頁面級>應用程式級>網站級>伺服器級。
換句話說,如果頁面設定為50分鐘,網站設定為120分鐘,那麼,顯然以50分鐘為生效的過期時間。
另外一個值得注意 的地方。
在設定二處,設定會話逾時(SessionState)120分鐘,而同時用forms認證,設定為“00:15:00”,即15分鐘,并且slidingExpirationo為false,則真正生效的Session過期時間是多少呢?
有效的結果是SessionState的設定,即120分鐘。
如果有設定Session過期時間沒有生效的,請檢查以上幾處配置。