我使用 MVC4 razor 构建了一个网站,我使用两种操作链接来重定向 View 。 “@Ajax.ActionLink”和“@Html.ActionLink”。我有一个单独的注销 View ,问题是如果我所在的 View 作为 @Ajax.Action 链接调用并且 session 过期,那么我的注销页面将在主布局 View 内打开。我想在单独的 View 中打开注销 View ,每当我使用部分 View 时都会发生同样的事情。
请让我知道如何使用 ajax.actionlink 解决此问题,否则部分 View 注销页面将在单独的 View 上打开。
提前致谢..
最佳答案
您需要做的涉及一些服务器端和客户端编码。
首先,在服务器端,您需要捕获用户 session 已过期并且他们正在使用 ajax 的请求。
如果您使用标准身份验证属性,您可以像这样扩展它:
public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
private class Http401Result : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = 401;
context.HttpContext.Response.Write("Your session has expired. Please login again to continue.");
context.HttpContext.Response.End();
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new Http401Result();
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
在 Controller 或操作上使用该属性而不是Authorize
。
现在到客户端,当请求从服务器返回并带有 401 响应时,您想要捕获它并执行某些操作,让我们使用 Ajax 设置来实现此目的:
坚持这个人,它将永远运行:
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
$(document).ajaxError(
function (e, request) {
if (request.status == 401) {
alert("Your session has expired. Please login again to continue.");
window.location = "/account/logon";
} else {
}
}
);
}
你就完成了。
关于jquery - mvc ajax 中的注销 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22130668/