Ridwan Bhugaloo
Ridwan Bhugaloo

Reputation: 241

Redirect to MVC view from Angular 12

From angular, I am trying a log out which will redirect me to the login page which is an mvc view.

So when the user clicks on the Log out, this executes:

this.http.post(`/Login/LogOff`, { params: undefined }).subscribe(result => {
    window.location.href = response.url;
});

Here is the controller (LoginController.cs):

[AllowAnonymous]
public ActionResult LogOff()
{
    //some code
    return this.RedirectToAction("Index", "Login");
}

The problem here is that I cannot modify the controller.

And I am getting an error on the console

SyntaxError: Unexpected token < in JSON at position 6 at JSON.parse () at XMLHttpRequest.l ........

But the status is 200.

Upvotes: 0

Views: 505

Answers (1)

P&#225;draig Galvin
P&#225;draig Galvin

Reputation: 1155

You are redirecting the Ajax request, not the browser.

When you make an Ajax request to an endpoint which returns a redirect to another page, your request is going to follow that redirect, download the HTML of the page and return the HTML as the response.

If you want the browser to follow the redirect, just set the browser location to the logout URL and let it follow the redirect natively.

  public logout() {
    window.location.pathname = '/Login/LogOff';
  }

You can manually redirect to the login page if the logout endpoint only accepts POST requests:

  public logout() {
    this.http.post(`/Login/LogOff`, null, { responseType:'text' }).subscribe(() => {
      window.location.pathname = '/Login';
    });
  }

Upvotes: 1

Related Questions