programing

ASP 유지NET 세션 오픈/얼라이브

starjava 2023. 4. 22. 08:23
반응형

ASP 유지NET 세션 오픈/얼라이브

이것이 ASP를 유지하는 가장 쉽고 방해받지 않는 방법입니다.사용자가 브라우저 창을 열어두면 NET 세션이 활성화됩니까?타이밍이 정해진 AJAX 콜입니까?다음 사항을 방지하고 싶습니다.사용자가 장시간 창을 열어 두었다가 내용을 입력하면 서버 측 세션이 만료되어 아무것도 작동하지 않을 수 있습니다.(브라우저 창을 닫음으로써) 타임아웃을 빠르게 하고 싶기 때문에 서버에서 타임아웃 값을 10분 이상 늘리지 않도록 합니다.

제안사항, 코드 샘플?

JQuery를 사용하여 더미의 HTTP 핸들러에 대한 간단한 AJAX 콜을 실행합니다.이 콜은 세션의 활성 상태를 유지하는 것 외에 아무것도 하지 않습니다.

function setHeartbeat() {
    setTimeout("heartbeat()", 5*60*1000); // every 5 min
}

function heartbeat() {
    $.get(
        "/SessionHeartbeat.ashx",
        null,
        function(data) {
            //$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :)
            setHeartbeat();
        },
        "json"
    );
}

세션 핸들러는 다음과 같이 단순할 수 있습니다.

public class SessionHeartbeatHttpHandler : IHttpHandler, IRequiresSessionState
{
    public bool IsReusable { get { return false; } }

    public void ProcessRequest(HttpContext context)
    {
        context.Session["Heartbeat"] = DateTime.Now;
    }
}

IRequiresSessionState를 추가하는 것이 중요합니다. 그렇지 않으면 세션을 사용할 수 없습니다(= null).일부 데이터를 호출하는 JavaScript로 반환해야 하는 경우 핸들러는 JSON 시리얼화 객체를 반환할 수도 있습니다.

web.config에서 입수 가능:

<httpHandlers>
    <add verb="GET,HEAD" path="SessionHeartbeat.ashx" validate="false" type="SessionHeartbeatHttpHandler"/>
</httpHandlers>

2012년 8월 14일에 balexandre에서 추가

저는 이 예를 너무 좋아해서 HTML/CSS와 비트 파트로 개선하고 싶습니다.

이것을 바꾸다

//$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :)

안으로

beatHeart(2); // just a little "red flash" in the corner :)

추가하다

// beat the heart 
// 'times' (int): nr of times to beat
function beatHeart(times) {
    var interval = setInterval(function () {
        $(".heartbeat").fadeIn(500, function () {
            $(".heartbeat").fadeOut(500);
        });
    }, 1000); // beat every second

    // after n times, let's clear the interval (adding 100ms of safe gap)
    setTimeout(function () { clearInterval(interval); }, (1000 * times) + 100);
}

HTML 및 CSS

<div class="heartbeat">&hearts;</div>

/* HEARBEAT */
.heartbeat {
    position: absolute;
    display: none;
    margin: 5px;
    color: red;
    right: 0;
    top: 0;
}

다음은 비트 파트만의 라이브 예시입니다.http://jsbin.com/ibagob/1/

ASP를 사용하는 경우.NET MVC – 추가 HTTP 핸들러 및 web.config 파일의 일부 변경은 필요하지 않습니다.필요한 것은 홈/공통 컨트롤러에 간단한 조작을 추가하는 것 뿐입니다.

[HttpPost]
public JsonResult KeepSessionAlive() {
    return new JsonResult {Data = "Success"};
}

다음과 같은 JavaScript 코드를 작성합니다(사이트의 JavaScript 파일 중 하나에 넣습니다).

var keepSessionAlive = false;
var keepSessionAliveUrl = null;

function SetupSessionUpdater(actionUrl) {
    keepSessionAliveUrl = actionUrl;
    var container = $("#body");
    container.mousemove(function () { keepSessionAlive = true; });
    container.keydown(function () { keepSessionAlive = true; });
    CheckToKeepSessionAlive();
}

function CheckToKeepSessionAlive() {
    setTimeout("KeepSessionAlive()", 5*60*1000);
}

function KeepSessionAlive() {
    if (keepSessionAlive && keepSessionAliveUrl != null) {
        $.ajax({
            type: "POST",
            url: keepSessionAliveUrl,
            success: function () { keepSessionAlive = false; }
        });
    }
    CheckToKeepSessionAlive();
}

JavaScript 함수를 호출하여 이 기능을 초기화합니다.

SetupSessionUpdater('/Home/KeepSessionAlive');

참고해주세요!이 기능은 인증된 사용자에게만 구현되어 있습니다(대부분 게스트의 세션 상태를 유지할 이유는 없습니다).세션 상태를 활성화 상태로 유지하려면 브라우저가 열려 있는지 여부에 따라 결정될 뿐만 아니라 인증된 사용자가 사이트에서 어떤 액티비티를 수행해야 합니다(마우스 이동 또는 키 입력).

서버에 요구를 할 때마다 세션타임아웃이 리셋 됩니다따라서 서버의 빈 HTTP 핸들러에 대해 Ajax 호출만 할 수 있지만 핸들러의 캐시가 비활성화되어 있는지 확인합니다.그렇지 않으면 브라우저는 핸들러를 캐시하여 새로운 요구를 하지 않습니다.

세션 유지Alive.ashx.cs

public class KeepSessionAlive : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
            context.Response.Cache.SetNoStore();
            context.Response.Cache.SetNoServerCaching();
        }
    }

JS:

window.onload = function () {
        setInterval("KeepSessionAlive()", 60000)
}

 function KeepSessionAlive() {
 url = "/KeepSessionAlive.ashx?";
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", url, true);
        xmlHttp.send();
        }

@vegerby - 세션에서 변수를 저장하는 데 드는 오버헤드가 필요하지 않습니다.서버에 대한 요청을 미리 작성하는 것만으로 충분합니다.

세션을 유지할 필요가 있습니까(데이터가 있습니까) 아니면 요청이 들어왔을 때 세션을 다시 구분하여 위장할 수 있습니까?첫 번째 경우 위의 방법을 사용합니다.두 번째인 경우 Session_End 이벤트핸들러를 사용해 보겠습니다

Forms Authentication이 있는 경우 Global.asax.cs에서 다음과 같은 정보를 얻을 수 있습니다.

FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(formsCookie.Value);
if (ticket.Expired)
{
    Request.Cookies.Remove(FormsAuthentication.FormsCookieName);
    FormsAuthentication.SignOut();
    ...             
     }
else
{   ...
    // renew ticket if old
    ticket = FormsAuthentication.RenewTicketIfOld(ticket);
    ...
     }

또한 티켓의 라이프 타임을 세션의 라이프 타임보다 훨씬 길게 설정합니다.인증을 하지 않거나 다른 인증 방식을 사용하는 경우에도 유사한 방법이 있습니다.Microsoft TFS Web 인터페이스와 SharePoint는 이러한 기능을 사용하고 있는 것 같습니다.이러한 정보는 오래된 페이지의 링크를 클릭하면 팝업창에 인증 프롬프트가 표시되지만 명령어만 사용하면 사용할 수 있습니다.

이 코드를 java 스크립트 파일에 쓰면 됩니다.

$(document).ready(function () {
        var delay = (20-1)*60*1000;
        window.setInterval(function () {
            var url = 'put the url of some Dummy page';
            $.get(url);                
        }, delay);
});

(20-1)*60*1000"Refresh of iis = " (전1분)는 입니다. × = - 합니다.새로 고침 시간 초과는 iis = 20분 중 기본 시간으로 계산됩니다. 즉, 20 × 60000 = 1200000 밀리초 - 60000 밀리초(세션 만료 1분 전)는 1140000입니다.

[파티에 늦게...]

Ajax 콜 또는 WebService 핸들러의 오버헤드를 없애기 위한 또 다른 방법은 특정 시간 후(즉, 세션스테이트 타임아웃 전, 통상은 20분)에 특별한 ASPX 페이지를 로드하는 것입니다.

// Client-side JavaScript
function pingServer() {
    // Force the loading of a keep-alive ASPX page
    var img = new Image(1, 1);
    img.src = '/KeepAlive.aspx';
}

KeepAlive.aspx는 그냥 빈입니다. ' '' '만지고' '만지고' '만지고' '만지고' '만지고' '만지고' '만지고' '만지고' '만지고' '만지고' '만지고' '만지고' '만' '만지고' '만'입니다.Session 삭제:

// KeepAlive.aspx.cs
public partial class KeepSessionAlive: System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Refresh the current user session
        Session["refreshTime"] = DateTime.UtcNow;
    }
}

'아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 이런img및가 ('이미지')에서합니다.KeepAlive.aspx 이 하면, 는 「업데이트」를 터치(갱신).Session오브젝트: 세션 만료 슬라이딩 시간 창(일반적으로 20분)을 연장합니다.실제 웹 페이지 내용은 브라우저에 의해 폐기됩니다.

하나의,깔끔한 '새로' '' '신규'는 '신규'iframe를 로드합니다.KeepAlive.aspx페이지 접속을 해 주세요.iframe숨겨져 를 들어, 숨겨진 「 가.div이 페이지의 어딘가에 있는 요소.

페이지 본문 전체에 대해 마우스와 키보드의 액션을 대행 수신함으로써 페이지 자체의 액티비티를 검출할 수 있습니다.

// Called when activity is detected
function activityDetected(evt) {
    ...
}

// Watch for mouse or keyboard activity
function watchForActivity() {
    var opts = { passive: true };
    document.body.addEventListener('mousemove', activityDetected, opts);
    document.body.addEventListener('keydown', activityDetected, opts);
}

저는 이 아이디어를 인정할 수 없습니다.https://www.codeproject.com/Articles/227382/Alert-Session-Time-out-in-ASP-Net을 참조하십시오.

클라이언트 PC가 sleep 모드가 되어도 존속할 수 있는 대체 솔루션을 다음에 나타냅니다.

로그인하고 있는 유저가 많은 경우는, 서버의 메모리를 대량으로 소비할 가능성이 있기 때문에, 신중하게 사용해 주세요.

로그인 후(로그인에서 이 작업을 수행합니다).로그인 제어의 경우)

Dim loggedOutAfterInactivity As Integer = 999 'Minutes

'Keep the session alive as long as the authentication cookie.
Session.Timeout = loggedOutAfterInactivity

'Get the authenticationTicket, decrypt and change timeout and create a new one.
Dim formsAuthenticationTicketCookie As HttpCookie = _
        Response.Cookies(FormsAuthentication.FormsCookieName)

Dim ticket As FormsAuthenticationTicket = _
        FormsAuthentication.Decrypt(formsAuthenticationTicketCookie.Value)
Dim newTicket As New FormsAuthenticationTicket(
        ticket.Version, ticket.Name, ticket.IssueDate, 
        ticket.IssueDate.AddMinutes(loggedOutAfterInactivity), 
        ticket.IsPersistent, ticket.UserData)
formsAuthenticationTicketCookie.Value = FormsAuthentication.Encrypt(newTicket)

사용자에게 세션을 갱신하거나 만료시킬 수 있는 옵션을 제공하는 팝업 대화 상자를 통해 WebForms에서 사용자 세션을 연장하는 방법을 알아보려고 며칠을 보냈습니다.당신이 알아야 할 가장 중요한 것은 다른 답변에서 이런 화려한 'HttpContext'가 필요하지 않다는 것이다.jQuery의 $.post(); 메서드만 있으면 됩니다.예를 들어 디버깅 중에 사용한 것은 다음과 같습니다.

$.post("http://localhost:5562/Members/Location/Default.aspx");

라이브 사이트에서는 다음과 같은 것을 사용합니다.

$.post("http://mysite/Members/Location/Default.aspx");

그만큼 쉽다.또한 세션을 갱신하는 옵션을 사용자에게 표시하려면 다음과 같은 작업을 수행합니다.

    <script type="text/javascript">
    $(function () { 
        var t = 9;
        var prolongBool = false;
        var originURL = document.location.origin;
        var expireTime = <%= FormsAuthentication.Timeout.TotalMinutes %>;

        // Dialog Counter
        var dialogCounter = function() {
            setTimeout( function() {
                $('#tickVar').text(t);
                    t--;
                    if(t <= 0 && prolongBool == false) {
                        var originURL = document.location.origin;
                        window.location.replace(originURL + "/timeout.aspx");
                        return;
                    }
                    else if(t <= 0) {
                        return;
                    }
                    dialogCounter();
            }, 1000);
        }

        var refreshDialogTimer = function() {
            setTimeout(function() { 
                $('#timeoutDialog').dialog('open');
            }, (expireTime * 1000 * 60 - (10 * 1000)) );
        };

        refreshDialogTimer();

        $('#timeoutDialog').dialog({
            title: "Session Expiring!",
            autoOpen: false,
            height: 170,
            width: 350,
            modal: true,
            buttons: {
                'Yes': function () {
                    prolongBool = true;
                    $.post("http://localhost:5562/Members/Location/Default.aspx"); 
                    refreshDialogTimer();
                    $(this).dialog("close");
                },
                Cancel: function () {
                    var originURL = document.location.origin;
                    window.location.replace(originURL + "/timeout.aspx");
                }
            },
            open: function() {
                prolongBool = false;
                $('#tickVar').text(10);
                t = 9;
                dialogCounter();
            }
        }); // end timeoutDialog
    }); //End page load
</script>

html에 대화 상자를 추가하는 것을 잊지 마십시오.

        <div id="timeoutDialog" class='modal'>
            <form>
                <fieldset>
                    <label for="timeoutDialog">Your session will expire in</label>
                    <label for="timeoutDialog" id="tickVar">10</label>
                    <label for="timeoutDialog">seconds, would you like to renew your session?</label>
                </fieldset>
            </form>
        </div>

vegerby의 솔루션에 대해 VB 앱에서 구현하려고 할 경우 제공된 코드를 번역기를 통해 실행하려고 할 때 주의하십시오.다음 기능이 작동합니다.

Imports System.Web
Imports System.Web.Services
Imports System.Web.SessionState

Public Class SessionHeartbeatHttpHandler
    Implements IHttpHandler
    Implements IRequiresSessionState

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        context.Session("Heartbeat") = DateTime.Now
    End Sub
End Class

또, 다음과 같이, 하트비트()와 같이 호출하는 대신에, 다음과 같이 기능합니다.

 setTimeout("heartbeat()", 300000);

대신 다음과 같이 부릅니다.

 setInterval(function () { heartbeat(); }, 300000);

첫째, set Timeout은 1회만 기동하지만 set은간격이 반복됩니다.둘째, 하트비트()를 문자열처럼 호출하는 것은 효과가 없었지만 실제 함수처럼 호출하는 것은 효과가 있었습니다.

그리고 이 솔루션이 Plesk에서 5분간의 앱풀 세션을 강제하는 GoDaddy의 터무니없는 결정을 극복할 수 있다는 것을 100% 확인할 수 있습니다.

핸들 최적화 기능이 있는 Maryan 솔루션의 JQuery 플러그인 버전입니다.JQuery 1.7+만!

(function ($) {
    $.fn.heartbeat = function (options) {
        var settings = $.extend({
            // These are the defaults.
            events: 'mousemove keydown'
            , url: '/Home/KeepSessionAlive'
            , every: 5*60*1000
        }, options);

        var keepSessionAlive = false
         , $container = $(this)
         , handler = function () {
             keepSessionAlive = true;
             $container.off(settings.events, handler)
         }, reset = function () {
             keepSessionAlive = false;
             $container.on(settings.events, handler);
             setTimeout(sessionAlive, settings.every);
         }, sessionAlive = function () {
             keepSessionAlive && $.ajax({
                 type: "POST"
                 , url: settings.url
                 ,success: reset
                });
         };
        reset();

        return this;
    }
})(jQuery)

*.cshtml로 Import하는 방법

$('body').heartbeat(); // Simple
$('body').heartbeat({url:'@Url.Action("Home", "heartbeat")'}); // different url
$('body').heartbeat({every:6*60*1000}); // different timeout

언급URL : https://stackoverflow.com/questions/1431733/keeping-asp-net-session-open-alive

반응형