【问题标题】:ASP.NET - Javascript timeOut Warning based on sessionState timeOut in web.configASP.NET - 基于 web.config 中 sessionState 超时的 Javascript 超时警告
【发布时间】:2011-08-11 16:06:17
【问题描述】:

问题:我希望根据我的 webconfig sessionState TimeOut 属性在一个带有 c# 代码的 asp.net 页面上创建一个超时警告消息。

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>

【问题讨论】:

    标签: c# javascript session-state session-timeout


    【解决方案1】:

    伪代码:

    • 读取代码隐藏中的超时设置
    • 注册一个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);
        }
    

    当然,您可以通过显示警告弹出窗口甚至是确认弹出窗口来改进客户端显示(而不是显示警报),然后您可以使用它来更新会话。

    【讨论】:

      【解决方案2】:

      我之前通过在我的代码隐藏文件中创建一个用于检查超时的 Web 方法来完成此操作。让您的 Javascript 函数通过 AJAX 获取超时信息并显示相应的警告。

      示例

      这是我的代码隐藏中的网络方法:

      [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,这表明发生了超时,并采取适当的措施。

      【讨论】:

      • AJAX 不是你使用的东西,而不是 Javascript。这是一种 Javascript 技术。我会举一个例子。
      • 我已经在我的答案中添加了一个示例,如果您愿意看一下。
      • 感谢您的示例和回复!
      【解决方案3】:

      我无法让 FishbasketGordo 的代码工作,因为 Web 方法调用一直将布尔值“false”作为 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
                      );
                  });
      

      【讨论】:

      • 实际上似乎对 web 方法的调用正在继续会话。我在一个页面上有时间通知,它在页面第一次加载时设置了一个会话变量,然后一个按钮将在同一个会话中打开第二个页面。第二个页面有一个按钮,用于检查会话变量是否存在,如果存在则更新标签,如果不存在则重定向到超时页面。每次超时通知报告会话超时,按钮报告会话变量仍然存在,表明会话实际上没有超时。
      【解决方案4】:

      试试这个解决方案(需要脚本管理器):

      <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>
      

      【讨论】:

        【解决方案5】:

        在我的博客中试试这个Seesion Alert Using Jquery

        • 会话设置为超时(例如 30 分钟)。
        • 当会话超时时,用户退出。
        • 显示倒计时,以便用户知道还剩多长时间。
        • 在用户接近限制时通知用户(例如,还剩 5 分钟)。
        • 让用户知道他们由于不活动而自动超时。

        【讨论】:

          【解决方案6】:

          我在我的 asp.net edit.aspx 页面上使用以下 javascript 代码创建了一个超时警告消息,要求用户在会话超时前保存数据 x 剩余分钟数:

          <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>
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-05-18
            • 2023-03-05
            • 2016-09-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-01-13
            • 1970-01-01
            相关资源
            最近更新 更多