2011-08-11 62 views
3

問題:我正在尋找在asp.net頁面上創建一個超時警告消息,其後面的c#代碼基於我的webconfig sessionState TimeOut屬性。在web.config中ASP.NET - Javascript超時警告基於sessionState timeOut在web.config

代碼:

<configuration> 
    <system.web> 
     <sessionState timeout="20"></sessionState> 
    </system.web> 
</configuration> 
<system.serviceModel> 
    <bindings> 
     <basicHttpBinding> 
      <binding name="EchoSignDocumentService10HttpBinding" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="6553600" maxBufferPoolSize="524288" maxReceivedMessageSize="6553600" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> 
       <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="1638400" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> 
       <security mode="Transport"> 
        <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> 
        <message clientCredentialType="UserName" algorithmSuite="Default" /> 
       </security> 
      </binding> 
      <binding name="EchoSignDocumentService10HttpBinding1" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> 
       <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> 
       <security mode="None"> 
        <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> 
        <message clientCredentialType="UserName" algorithmSuite="Default" /> 
       </security> 
      </binding> 
     </basicHttpBinding> 
    </bindings> 
</system.serviceModel> 

回答

1

我已經創造了我的代碼隱藏文件的Web方法來檢查超時這樣做過。讓您的Javascript函數通過AJAX獲取超時信息並根據警告顯示警告。

這是我的代碼隱藏Web方法:

[WebMethod] 
public static bool HasSessionTimedOut() 
{ 
    HttpSessionState session = HttpContext.Current.Session; 

    // I put this value into Session at the beginning. 
    DateTime? sessionStart = session[SessionKeys.SessionStart] as DateTime?; 

    bool isTimeout = false; 

    if (!sessionStart.HasValue) 
    { 
     isTimeout = true; 
    } 
    else 
    { 
     TimeSpan elapsed = DateTime.Now - sessionStart.Value; 
     isTimeout = elapsed.TotalMinutes > session.Timeout; 
    } 

    return isTimeout; 
} 

這是我的javascript:

<script type="text/javascript">         
    $(function() {             
     var callback = function(isTimeout) { 
      if (isTimeout) {       
       // Show your pop-up here... 
      }       
     };               
     setInterval(            
      function() { 
       // Don't forget to set EnablePageMethods="true" on your ScriptManager. 
       PageMethods.HasSessionTimedOut(false, callback);  
      },              
      30000             
     );               
    });                
</script> 

所以,這是很基本的。每30秒,我的Javascript函數就會使用ASP.NET的PageMethods對象向我的web方法發送一個AJAX請求。它會在回調中檢查返回值true,表示發生了超時,並採取適當的操作。

+0

AJAX不是用來對付Javascript的東西。這是一種JavaScript技術。我將以一個例子爲例。 – FishBasketGordo

+0

我已經給我的答案添加了一個例子,如果你喜歡看一看。 – FishBasketGordo

+0

感謝您的例子和迴應! –

2

僞代碼:

  • 閱讀超時的代碼隱藏
  • 設置註冊一個ClientScriptblock(setTimeout經過超時週期(20 * 60))
  • 在超時,在頁面上顯示一個警告標籤

示例代碼:

public void RegisterTimeoutWarning(System.Web.UI.Page Page) 
    { 
     var timeout = HttpContext.Current.Session.Timeout * 60 * 1000; 
     Page.ClientScript.RegisterStartupScript(Page.GetType(), 
       "timeoutWarning", 
       string.Format("setTimeout(function() {{ alert('Session about to expire'); }}, {0});", timeout), true); 
    } 

當然,您可以通過顯示警告彈出窗口甚至確認彈出窗口來改進客戶端顯示(而不是顯示警報),然後您可以使用該窗口來更新會話。

1

嘗試這種解決方案(需要一個腳本經理):

<script type="text/javascript"> 

    //get a hold of the timers 
    var iddleTimeoutWarning = null; 
    var iddleTimeout = null; 

    //this function will automatically be called by ASP.NET AJAX when page is loaded and partial postbacks complete 
    function pageLoad() { 

     //clear out any old timers from previous postbacks 
     if (iddleTimeoutWarning != null) 
      clearTimeout(iddleTimeoutWarning); 
     if (iddleTimeout != null) 
      clearTimeout(iddleTimeout); 
     //read time from web.config 
     var millisecTimeOutWarning = <%= int.Parse(System.Configuration.ConfigurationManager.AppSettings["SessionTimeoutWarning"]) * 60 * 1000 %>; 
     var millisecTimeOut = <%= int.Parse(System.Configuration.ConfigurationManager.AppSettings["SessionTimeout"]) * 60 * 1000 %>; 

     //set a timeout to display warning if user has been inactive 
     iddleTimeoutWarning = setTimeout("DisplayIddleWarning()", millisecTimeOutWarning); 
     iddleTimeout = setTimeout("TimeoutPage()", millisecTimeOut); 
    } 

    function DisplayIddleWarning() { 
     alert("Your session is about to expire due to inactivity."); 
    } 

    function TimeoutPage() { 
     //refresh page for this sample, we could redirect to another page that has code to clear out session variables 
     location.reload(); 
    } 

</script> 
1

我使用下面的JavaScript創建了一個超時警告消息askign用戶的會話超時前的數據保存出剩餘分鐘的X號我的asp.net edit.aspx頁面代碼:

<script language="javascript" type="text/javascript"> 
    var sessionTimeoutWarning = "<%= System.Configuration.ConfigurationSettings.AppSettings["SessionWarning"].ToString()%>"; 
    var sessionTimeout = "<%= Session.Timeout %>"; 

    var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000; 
    setTimeout('SessionWarning()', sTimeout); 

    function SessionWarning() 
    { 
     var message = "Your session will expire in another " + (parseInt(sessionTimeout) - parseInt(sessionTimeoutWarning)) + " mins! Please Update the data before the session expires"; 
     alert(message); 
    } 
</script> 

我警告消息的頻率設置爲每隔20分鐘,並使其易於通過將它作爲下的應用程序設置的變量,這也是改變在web.config中可訪問並定義作爲一個關鍵(SessionWarning)w /值爲20(代表20分鐘)。

這是我在我的web.config文件中使用的代碼:

<configuration> 
    <appSettings> 
     <add key="SessionWarning" value="20" /> 
     <add key="EchoSignApiKey" value="XZKZ3VT2M*****" /> 
     <add key="EchoSignSignedDocumentUrl" value="http://echosign:*****.Com/ApplicationFiles/" /> 
     <!-- dummy --> 
     <add key="ImageSaveFolder" value="C:\Development\Temp" /> 
     <add key="FileSaveFolder" value="C:\Development\Temp" /> 
     <!-- Test Library--> 
     <add key="AS400LIBRARY" value="TPATSTDTA" /> 
     <add key="AllowVoiceSignature" value="False" /> 
    </appSettings> 
    <system.web> 
     <sessionState timeout="60" /> 
    </system.web> 
    <system.serviceModel> 
     <bindings> 
      <basicHttpBinding> 
       <binding name="EchoSignDocumentService10HttpBinding" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="6553600" maxBufferPoolSize="524288" maxReceivedMessageSize="6553600" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> 
        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="1638400" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> 
        <security mode="Transport"> 
         <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> 
         <message clientCredentialType="UserName" algorithmSuite="Default" /> 
        </security> 
       </binding> 
       <binding name="EchoSignDocumentService10HttpBinding1" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> 
        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> 
        <security mode="None"> 
         <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> 
         <message clientCredentialType="UserName" algorithmSuite="Default" /> 
        </security> 
       </binding> 
      </basicHttpBinding> 
     </bindings> 
    </system.serviceModel> 
</configuration> 
2

我是不是能夠得到FishbasketGordo的代碼工作,因爲Web方法調用保持傳遞布爾值「假」爲的onSuccess方法。經過很多研究,我做了以下更改。

  $(function() { 
       var isTimeout = false; 
       var callback = function (isTimeout) { 
        if (isTimeout) { 
         // Show your pop-up here... 
         alert("You have timed out"); 
        } 
       }; 

       var failure = function() { 
        alert("Problem with Server"); 
       }; 

       setInterval(
         function() { 
          // Don't forget to set EnablePageMethods="true" on your ScriptManager. 
          PageMethods.HasSessionTimedOut(callback,failure); 
         }, 30000 
       ); 
      }); 
+1

實際上,對web方法的調用似乎正在繼續會話。我在一個頁面上有時間通知,當頁面首次加載時設置一個會話變量,然後一個按鈕將在同一個會話中打開第二個頁面。第二頁有一個按鈕,用於檢查會話變量是否存在,如果存在則更新標籤,如果不存在,則將其重定向到超時頁面。每當超時通知報告會話超時,按鈕報告的會話變量仍然存在,表明會話實際上沒有超時。 – user1161391

1

從我的博客試試這個Seesion Alert Using Jquery

  • 會話設置超時(如30分鐘)。
  • 會話超時後,用戶已註銷。
  • 顯示倒計時,以便用戶知道剩下的時間。
  • 當用戶接近極限時通知用戶(例如,剩下5分鐘)。
  • 讓用戶知道他們由於不活動而自動超時。