8

部分ビューを返す MVC への ajax 呼び出しがあります。これは、セッションが終了するか、Cookie の有効期限が切れるまで問題ありません。ajax 呼び出しを行うと、部分ビュー用の div 内にコンテンツが表示されます。ajax 呼び出し中にセッションの有効期限が切れたことを検出し、フルスクリーン/ページに適切にリダイレクトするにはどうすればよいですか?

4

3 に答える 3

5

すべてのリクエストをラッパー要素にカプセル化することをお勧めします。

public class JsonResponse<T>
{
    public JsonResponse()
    {
    }

    public JsonResponse(T Data)
    {
        this.Data = Data;
    }

    public T Data { get; set; }
    public bool IsValid { get; set; }
    public string RedirectTo { get; set; }
}

クライアントに送信するモデルは Data にあります。

RedirectTo を設定するために、 Global.Asax でGlobalAuthorize属性を使用し、 HandleUnauthorizedRequests のハンドルを追加しました。

public sealed class GlobalAuthorize : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest
      (AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.Result = new JsonResult
            {
                Data = new JsonResponse<bool>
                       {
                           IsValid = false,
                           //RedirectTo = FormsAuthentication.LoginUrl
                           RedirectTo = "/"
                       },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    } 

さらに、すべての Ajax リクエストを単一の関数にカプセル化して、 RedirectTo.

function global_getJsonResult(Controller, View, data, successCallback, completeCallback, methodType)
{
    if (IsString(Controller)
        && IsString(View)
        && !IsUndefinedOrNull(data))
    {
        var ajaxData;
        var ajaxType;

        if (typeof (data) == "string")
        {
            ajaxData = data;
            ajaxType = "application/x-www-form-urlencoded"
        }
        else
        {
            ajaxData = JSON.stringify(data);
            ajaxType = "application/json; charset=utf-8";
        }
        var method = 'POST';

        if (!IsUndefinedOrNull(methodType)) 
        {
            method = methodType;
        }

        var jqXHR = $.ajax({
            url: '/' + Controller + '/' + View,
            data: ajaxData,
            type: method,
            contentType: ajaxType,
            success: function(jsonResult)
            {
                if (!IsUndefinedOrNull(jsonResult)
                    && jsonResult.hasOwnProperty("RedirectTo")
                    && !IsUndefinedOrNull(jsonResult.RedirectTo)
                    && jsonResult.RedirectTo.length > 0)
                {
                    $.fn.notify('error', 'Login Expired', 'You have been inactive for a prolonged period of time, and have been logged out of the system.');
                    window.setTimeout(function() { window.location = jsonResult.RedirectTo }, 5000);
                }
                else if (IsFunction(successCallback))
                {
                    successCallback(jsonResult, Controller + '/' + View);
                }
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                if (errorThrown != 'abort')
                {
                    $.fn.notify('error', 'AJAX Connection Error', textStatus + ': ' + errorThrown);
                }

            },
            complete: function(jqXHR, textStatus)
            {
                if (IsFunction(completeCallback))
                {
                    completeCallback(jqXHR, textStatus, Controller + '/' + View);
                }
            }
        });

        return jqXHR;
    }
}
于 2012-05-14T20:39:56.717 に答える
4

セッションがタイムアウトしたときにユーザーにダイアログを表示するJavaScriptを使用して、クライアントにタイマーを作成できます。タイマーの値をセッションのタイムアウトに設定するだけです。次に、ajaxリクエストで、カウントダウンもリセットします。

var g_sessionTimer = null;
function uiSessionInit() {
    id = "uiTimeout";
    timeout = 3600000 * 24; // 1 day timeout
    uiSessionSchedulePrompt(id, timeout);
    $('body').ajaxStart(function () {
        // reset timer on ajax request
        uiSessionSchedulePrompt(id, timeout);
    });
}
function uiSessionSchedulePrompt(id, timeout) {
    if (g_sessionTimer)
        clearTimeout(g_sessionTimer);
    g_sessionTimer = setTimeout(function () { uiSessionExpiring(id); }, timeout);
}
function uiSessionExpiring(id) {
    // create a dialog div and use this to show to the user
    var dialog = $('<div id="uiTimeout"></div>').text("Your session with has timed out. Please login again.");
    $('body').append(dialog);
    $('#uiTimeout').dialog({ 
           autoOpen: true, 
           modal: true, 
           title: 'Expired Session', 
           buttons: { 
                "OK": function(){
                    $(this).dialog('close'); 
                }
           },
           close: uiSessionDialogClose
     });
}

function uiSessionDialogClose(){
    // take user to sign in location
    location = 'http://www.mypage.com'; 
}
于 2012-05-14T20:39:47.307 に答える