在我的 MVC3 应用程序中,有几种情况,我会显示一个启动屏幕,通过 jQuery 的 ajax 方法动态加载部分 View 并将 html 注入(inject) DOM。
问题是,如果身份验证过期,然后用户发起 ajax 调用,被调用的操作将重定向到登录页面,因此返回登录页面的 html 并注入(inject)到 DOM 中,这显然是在进行让用户感到非常困惑。
人们通常如何处理这种情况?我想这很常见,因为表单例份验证和 ajax 对 html 的请求是我经常做的事情。
最佳答案
这是我为这种情况编写的 AuthorizeAjax 操作过滤器,您可以按如下方式使用它:
[AuthorizeAjax]
public ActionResult GetNewData()
{
//controller logic here
}
通过将以下内容添加到您的项目中,您所需要的只是共享文件夹中名为“AjaxAccessError”的部分 View ,就我个人而言,我返回一个指向真实登录页面的链接:)
希望这有帮助!
namespace System.Web.Mvc
{
public class AuthorizeAjaxAttribute : AuthorizeAttribute
{
private bool _failedAuthorisation;
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.User.Identity.IsAuthenticated)
{
_failedAuthorisation = true;
return false;
}
else
{
String[] RoleArray = Roles.Split(',');
foreach (var r in RoleArray)
{
if (httpContext.User.IsInRole(r))
{
_failedAuthorisation = false;
return true;
}
}
_failedAuthorisation = true;
return false;
}
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (_failedAuthorisation)
{
filterContext.Result = new PartialViewResult { ViewName = "AjaxAccessError" };
}
}
}
}
关于c# - 在ajax请求期间处理MVC表单例份验证过期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6508163/