【问题标题】:Dealing with MVC forms authentication expiration during ajax request [duplicate]在ajax请求期间处理MVC表单身份验证到期[重复]
【发布时间】:2011-09-24 09:20:39
【问题描述】:

在我的 MVC3 应用程序中,有几种情况我会显示启动画面,通过 jQuery 的 ajax 方法动态加载部分视图并将 html 注入 DOM。

问题是,如果身份验证过期,然后用户发起 ajax 调用,被调用的操作会重定向到登录页面,所以登录页面的 html 被返回并注入到 DOM 中,这显然是在进行给用户带来极大的困惑。

人们通常如何处理这种情况?我想这很常见,因为我经常做 html 的表单 auth 和 ajax 请求。

【问题讨论】:

    标签: c# jquery ajax asp.net-mvc-3


    【解决方案1】:

    这是我针对这种情况编写的 AuthorizeAjax 操作过滤器,您可以按如下方式使用它:

    [AuthorizeAjax]
    public ActionResult GetNewData()
    {
        //controller logic here
    }
    

    通过将以下内容添加到您的项目中,您所需要的只是共享文件夹中名为“AjaxAccessError”的部分视图,我个人返回一个指向真实登录页面的链接:)

    希望这会有所帮助!

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

    【讨论】:

    • 您最终不会因为 FormsAuthentication 模块而返回 302 吗?
    猜你喜欢
    • 1970-01-01
    • 2020-02-03
    • 2011-10-27
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多