gpt4 book ai didi

asp.net-mvc-3 - 当用户需要再次登录时,Ajax.ActionLink 在 div 内返回登录页面

转载 作者:行者123 更新时间:2023-12-03 00:06:40 25 4
gpt4 key购买 nike

我有一个Ajax.ActionLink,它会返回部分 View 。但是,如果我的 FormsAuthentication 过期并且用户需要再次登录,则整个登录页面将作为部分 View 返回。

这会导致完整的登录页面出现在我为部分 View 预留的 div 中。所以页面上看起来就像是两个网页。

我在 Controller 和操作上使用[Authorize] 属性。

如何强制登录页面以完整 View 形式返回?

最佳答案

您可以扩展 [Authorize] 属性,以便可以重写 HandleUnauthorizedRequest 函数以将 JsonResult 返回到 AJAX 调用。

public class AuthorizeAjaxAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext
filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
// It was an AJAX request => no need to redirect
// to the login url, just return a JSON object
// pointing to this url so that the redirect is done
// on the client

var referrer = filterContext.HttpContext.Request.UrlReferrer;

filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { redirectTo = FormsAuthentication.LoginUrl +
"?ReturnUrl=" +
referrer.LocalPath.Replace("/", "%2f") }
};
}
else
base.HandleUnauthorizedRequest(filterContext);
}
}

创建一个 Javascript 函数来处理重定向:

<script type="text/javascript">
function replaceStatus(result) {
// if redirectTo has a value, redirect to the link
if (result.redirectTo) {
window.location.href = result.redirectTo;
}
else {
// when the AJAX succeeds refresh the mydiv section
$('#mydiv').html(result);
}
};
</script>

然后在 Ajax.ActionLink 的 OnSuccess 选项中调用该函数

Ajax.ActionLink("Update Status", "GetStatus", 
new AjaxOptions { OnSuccess="replaceStatus" })

关于asp.net-mvc-3 - 当用户需要再次登录时,Ajax.ActionLink 在 div 内返回登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8304689/

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