【问题标题】:Error 302 when trying to redirect from API Controller尝试从 API 控制器重定向时出现错误 302
【发布时间】:2019-12-12 06:28:47
【问题描述】:

redirecting 显示正在调用的页面并显示 302 错误。我该如何处理它允许我通过 API 方法重定向到页面并在凭据错误时显示错误消息。我宁愿避免使用window.location.href,因为传入 RedirectUrl 不起作用。

API 方法

[HttpPost]
[AllowAnonymous]
[Route("Login")]
public async Task<IActionResult> Login([FromForm] LoginViewModel model)
{
    if (model.Username == "user" && model.Password == "password")
    {
        Redirect("/User/Index");
    }
    else return StatusCode(400, "Invalid user or password");
}

AJAX 调用

$("#loginBtn").on('click', function (e) {
    e.preventDefault();
    $.ajax({
        url: '/api/Account/Login',
        type: 'POST',
        data: $('#loginForm').serialize()
    })
        .done(function (data) {
        })
        .fail(function () {
                $('#errorMessage').append("Invalid username or password").show();
                $('#errorMessage').removeAttr('id');
            }
        });
});


编辑: 根据 Athanasios Kataras 的解释,我决定改用错误消息。我想出了这个解决方案:
$("#loginBtn").on('click', function (e) {
    e.preventDefault();
    $.ajax({
        url: '/api/Account/Login',
        type: 'POST',
        data: $('#loginForm').serialize()
    })
        .done(function (data) {
        })
        .fail(function () {
                sessionStorage.setItem("error", "Error");
                location.reload();
            }
        });
});

if (sessionStorage.getItem("error") != null) {
    $('#errorMessage').html("Invalid username or password").show();
    sessionStorage.removeItem("error");
}

【问题讨论】:

    标签: javascript c# jquery ajax asp.net-core


    【解决方案1】:

    您不能通过 XHR 请求重定向。当返回 302 时,浏览器会立即跟随它并在新的 url 处寻找 ajax 响应。

    如果是完整的回传而不是 xhr/ajax 请求,它将正确重定向。

    过去您甚至看不到重定向,但现在它就在那里。

    老实说,除了window.location.href,我没有看到其他方法。

    也许,您可以通过使用它来获取状态,但我已经检查了一下。可能是这样你就可以捕捉到 302 并进行适当的处​​理。

    $.ajax( url [, settings ] )
        .always(function (jqXHR) {
            console.log(jqXHR.status);
     });
    

    【讨论】:

    • 非常感谢您的解释。我决定改用错误处理的解决方法。
    • 很高兴我能帮上忙
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2023-03-16
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    相关资源
    最近更新 更多