c# - 在ajax请求期间处理MVC表单例份验证过期

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

在我的 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/

相关文章:

c# - 只能在 DependencyObject 的 DependencyProperty 上设置 'Binding'

javascript - 从 div 或模板中获取所有 Handlebars 表达式?

javascript - 如何在浏览器的另存为对话框中更改自动填充的文件名?

php - Yii2 提交模态表单后不刷新页面

javascript - 从 JavaScript 调用 ASP.NET Web 服务方法

jquery - 动态填充其他选择选项,但我希望它仅显示在同一个父类中

c# - NAudio - 如何将正弦波仅发送到插孔上的一个音频 channel

c# - 如何在 ASP.Net MVC 中创建 bool HTML5 属性 'conditional'?

c# - 在 Facebook 应用程序中获取 friend 的电子邮件

javascript - 在焦点上显示和隐藏不同的元素