vierbot
vierbot

Reputation: 11

Error 302 when trying to redirect from API Controller

Upon redirecting shows me the page being called and 302 error being shown. How do I handle this where it allows me to redirect to the page via API method and show an error message if the credentials are wrong. I would prefer to refrain from using window.location.href as passing in RedirectUrl doesn't work.

API method

[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 Call

$("#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');
            }
        });
});


Edit: From Athanasios Kataras explanation, I decided play around with the error message instead. I came up with this solution:

$("#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");
}

Upvotes: 1

Views: 403

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26450

You can't redirect via XHR requests. When the 302 is returned, the browser will follow it at once and look for an ajax response at the new url.

If it's a full post back and not xhr/ajax request, it will redirect properly.

In the past you wouldn't even see the redirect but now it is there.

I don't see another way other than window.location.href to be honest.

Maybe though, you can get the status by using this, but I have bit checked it. It could be that in this way you can catch the 302 and handle it appropriately.

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

Upvotes: 1

Related Questions