ASP.NET - 基于 web.config 中的 sessionState 超时的 Javascript 超时警告

发布于 2024-11-29 09:15:22 字数 2298 浏览 0 评论 0原文

问题:我希望在基于 webconfig sessionState TimeOut 属性的 ac# 代码后面的 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>

Problem: I am looking to create a time-out warning message on an asp.net page with a c# code behind based off my webconfig sessionState TimeOut Attribute.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

国际总奸 2024-12-06 09:15:22

伪代码:

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

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

Pseudo code:

  • Read the timeout setting in codebehind
  • Register a ClientScriptblock (setTimeout passing the timeout period (20 * 60))
  • On timeout, display a warning label on the page

Sample code:

    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);
    }

Of course, you can improve the client side display (rather than showing an alert) by displaying warning popups or even a confirm popup which you can then use to renew the session.

[旋木] 2024-12-06 09:15:22

我之前已经通过在代码隐藏文件中创建一个 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(这表明发生了超时),并采取适当的操作。

I've done this before by creating a web method in my code-behind file that checks for the timeout. Have your Javascript function get the timeout information via AJAX and display a warning according.

Example

This is the web method in my code-behind:

[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;
}

And this is my 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> 

So, this is pretty rudimentary. Every 30 seconds, my Javascript function sends an AJAX request to my web method using ASP.NET's PageMethods object. It checks for a return value of true in the callback, which indicates that a timeout has occurred, and takes the appropriate action.

葬﹪忆之殇 2024-12-06 09:15:22

我无法让 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
                );
            });

I was not able to get FishbasketGordo's code to work because the Web Method call kept passing the Boolean value "false" as the onsuccess method. After much research I made the following changes.

            $(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
                );
            });
半衾梦 2024-12-06 09:15:22

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

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

Try this solution (requires a script manager):

<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>
原野 2024-12-06 09:15:22

尝试一下 使用 Jquery 的 Seesion Alert我的博客:

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

Try This Seesion Alert Using Jquery from my blog:

  • Session set to time out (e.g. 30 minutes).
  • When session times out, the user is logged out.
  • Display a countdown so the user knows how long is left.
  • Inform the user when they are approaching the limit (e.g. 5 minutes left).
  • Let the user know that they’ve been automatically timed out due to inactivity.
青衫负雪 2024-12-06 09:15:22

我在我的 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),其值为 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>

I created a time-out warning message askign the user to save data before the session times out in x number of remaining minutes using the following javascript code on my asp.net edit.aspx page:

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

I set the frequency of the warning message to every 20 minutes and made it easy to change by putting it as a variable under the application settings, which is also accessible in the web.config under and defined as a key (SessionWarning) w/ a value to 20 (representing 20 minutes).

Here's the code I used on my web.config file:

<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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文