MVC 3/Jquery AJAX/Session Expires/C# - 处理会话超时djng ajax调用

Arc*_*ian 7 asp.net-mvc jquery session-timeout session-cookies

我有一个对MVC的ajax调用,它返回一个partialview.在会话结束或cookie过期之前,这一切都很好.当我进行ajax调用时,它会显示div中的内容,该div用于部分视图.如何在ajax调用期间检测到我的会话已过期并正确地重定向到完整屏幕/页面

Eri*_*ips 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; }
}
Run Code Online (Sandbox Code Playgroud)

您想要发送给客户的模型是Data.

为了得到填充RedirectTo,我使用GlobalAuthorize在Global.asax属性,并增加了手柄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);
        }
    } 
Run Code Online (Sandbox Code Playgroud)

另外,我已将所有 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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Gab*_*abe 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'; 
}
Run Code Online (Sandbox Code Playgroud)