Miguel Moura
Miguel Moura

Reputation: 39484

Redirect from API action to MVC action

I am using ASP.NET Core RC1 and I have an API action which is being called by the client using Angular:

[HttpPost("account/signin")]
public async Task<IActionResult> SignIn([FromBody]SignInModel model) {

  if (ModelState.IsValid) {

    // Redirect to Home/Index here

  } else {       

    return HttpBadRequest();

  }

}

How to redirect from this action that is called by the client to the Home/Index action to load that page?

Upvotes: 0

Views: 837

Answers (1)

Mark Hughes
Mark Hughes

Reputation: 7374

You'll need to handle the redirection in Angular, not on the server. Your sign in API should return an indication of success to Angular, then in your Angular controller that called the API, you'll need to check the response value and make the transition to the relevant page.

If you return a redirect response from the API, Angular will simply follow that redirect then receive the content of the Home/Index into its HTTP request object, which is unlikely to be what you want.

API method:

[HttpPost("account/signin")]
public async Task<IActionResult> SignIn([FromBody]SignInModel model) {

    if (ModelState.IsValid) {
        return new { Authenticated = true };
    } else {       
        return HttpBadRequest();
    }
}

Here's an example of the sort of handling code you might want in your Angualar controller (this assumes "/" is the URL for Home/Index):

$http.post(
    "account/signin",
    { "Username": vm.username, "Password": vm.password }
).then(function (authResponse) {
    if (authResponse.data.Authenticated) {
        // Reload the page:
        $window.location.href = "/";
    } else {
        vm.success = false;
        vm.failMessage = "Login unsuccessful, please try again.";
    }
}, function (errResponse) {
    // Error case.
    vm.failMessage = "Unable to process login - please try again."
});

Upvotes: 2

Related Questions