Kirzy
Kirzy

Reputation: 148

WebApi redirect to external site

I have a WebApi controller that after I invoke it I want it to redirect me to another site

Here is my c# code

public async Task<HttpResponseMessage> Login(LoginParameters parameters, [FromUri]string returnUrl)
{
    //same validations
    var response = Request.CreateResponse(HttpStatusCode.Moved);

    response.Headers.Location = new Uri("Http://www.google.com");

    return response;
}

My javascript code goes like this

'user strict'
var login = function ($scope, $http) {

    var parameters = {
        userName: userName,
        password: password
    };

    var url = '/api/user/Login';

    $http.post(url, parameters);
        .then(function(response){
            /*some random code that i will remove */
        });
};

login.$inject = ['$scope', '$http'];
module.exports = login;

Looking at the chrome console i realise that the http POST call returns httpstatus = 302. Then i see 2 more request to requests to google.com, but my page is not redirected. So what am I doing wrong?

Thanks in advance

Upvotes: 2

Views: 1096

Answers (2)

Zach
Zach

Reputation: 3207

I would recommend you look into angular interceptors. You can "intercept" the response, check the status code, and redirect using window.location or $location. This is pretty flexible so you write the logic in one place.

Edit: this doesn't seem to work because it appears you can't catch a 302. According to this post, it appears the request is redirected automatically and the response you'd get back is from the redirected location. In the OP's post - the response was empty because the OP was redirected to a different domain which resulted in a cross-domain request (so keep this in mind if your redirects will do the same), but a proposed solution was to check the response to see if it contained data from the redirected page.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190907

When you use $http, this uses an XMLHttpRequest object which does not adjust the location for the user. It will even follow redirects. You have a couple options:

  • You could return the new location as a field, then in the .then callback, assign window.location to cause a redirect.

  • You could use a standard form to post to the resource, then the browser would follow the redirects appropriately.

Upvotes: 2

Related Questions