【问题标题】:ajax mvc form authentication redirect issueajax mvc 表单身份验证重定向问题
【发布时间】:2017-02-08 13:26:02
【问题描述】:

我正在尝试在 MVC 表单身份验证中处理失败的 ajax 请求。我在 Global.asax 中添加了以下代码。

protected void Application_BeginRequest()
    {
        HttpRequestBase request = new HttpRequestWrapper(Context.Request);
        if (request.IsAjaxRequest())
        {
            Context.Response.SuppressFormsAuthenticationRedirect = true;
        }
    }

在主布局上,我添加了以下代码

 $(document).ajaxError(function (event, request, settings) {
            if (request.status == 401) {
                window.location.href = '@Url.Action( "Login", "Account" )';
            }
         });

问题 1: 在正常调用中,表单身份验证会重定向到登录页面以及返回 url,这将帮助用户返回到他在到期前上次访问的同一页面。 http://localhost:53733/Account/Login?ReturnUrl=%2fUser%2fUserList

自从我使用 jQuery 重定向后,在 ajax 调用期间,它是 http://localhost:53733/Account/Login。如何确保即使在 ajax 调用中它也会与返回 url 一起重定向到登录页面

问题 2: 本地 ajax 函数错误处理程序也会在全局 ajax 错误处理程序之前触发。这会导致在导航到登录页面之前在页面上显示错误。不知道如何处理。请指教。

【问题讨论】:

    标签: jquery ajax asp.net-mvc authentication form-authentication


    【解决方案1】:

    您可以将当前 url 作为 returnUrl 发送

    var u = '@Url.Action( "Login", "Account" )?ReturnUrl='+window.location.href;
    window.location.href = u;
    

    请记住,成功登录后,您的 Login 操作方法将重定向到 returnUrl 值,这将是一个全新的 GET 请求。因此用户会将页面视为新页面加载(它会丢失您在重定向之前在页面中所做的任何更改)

    对于第二个问题,在你的本地ajax函数中,如果request.status == 401不处理

    类似

    $.ajax({
        url: "someUrl",
        type: "post"
    }).done(function(f) {
        console.log('done');
    }).fail(function(a, b, c) {
        if (a.status !== 401) {
           // Handle locally as needed.
        }
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 2019-11-16
    • 2022-01-19
    • 1970-01-01
    相关资源
    最近更新 更多