gpt4 book ai didi

asp.net-mvc - MVC 3/Jquery AJAX/Session Expires/C# - 在ajax调用期间处理 session 超时

转载 作者:行者123 更新时间:2023-12-03 22:39:07 25 4
gpt4 key购买 nike

我有一个对 MVC 的 ajax 调用,它返回一个局部 View 。在 session 结束或 cookie 过期之前一切都很好。当我进行 ajax 调用时,它会显示 div 内的内容,该内容本来是用于部分 View 的。如何在 ajax 调用期间检测我的 session 已过期并正确重定向到全屏/页面

最佳答案

我建议将所有请求封装到包装元素中:

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

您要发送给客户的模型位于数据中。

为了填充 RedirectTo,我使用 GlobalAuthorize Global.Asax 中的属性并添加了 handle for 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;
}
}

关于asp.net-mvc - MVC 3/Jquery AJAX/Session Expires/C# - 在ajax调用期间处理 session 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10590572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com