admin管理员组

文章数量:1236712

Problem: I am looking to create a time-out warning message on an asp 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>

Problem: I am looking to create a time-out warning message on an asp 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>
Share Improve this question edited Aug 29, 2013 at 18:34 KyleMit 30k72 gold badges506 silver badges698 bronze badges asked Aug 11, 2011 at 16:06 Brian McCarthyBrian McCarthy 4,78417 gold badges51 silver badges66 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 3

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.

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.

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

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

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

本文标签: cASPNETJavascript timeOut Warning based on sessionState timeOut in webconfigStack Overflow