Ajax call does not redirect based on Redirect 302 of webapi

Viewed 29

I have a c# webapi application where the endpoint just redirects, however, when I call from an HTML page that has an AJAX call, it does not redirect, could you please help me where I'm missing? I tried all combinations.

 [HttpPost]
        [Route("Redirect")]
        public async Task<IActionResult> Redirect()
        {
            var response = "https://google.com";
            return Redirect(response);
        }

AJAX call

$.ajax({
   url: "https://10.10.45.2/api/Redirect", 
   type: "POST",
   dataType: "json",
 contentType: "application/json; charset=utf-8",
 success: function(data, textStatus, xhr) {
        window.location = xhr.location;   // I know this is not correct
    },
    complete: function(xhr, textStatus) {
        console.log("Complete: " + xhr.status);
    }, 
    error: function (jqXHR, timeout, message) {
        console.log("Complete: " + jqXHR.status);
        console.log("Response Location :" + loginPageRedirectHeader);
    }
});
1 Answers

In short, when ajax sends a request, the data you get should be the json type you agreed on. Redirect will not send matching data back, so your code is wrong and cannot achieve this requirement.

Ajax is used to send http requests, and the sending method and receiving format need to be defined by themselves. In your scenario, it is recommended to use window.location to jump after receiving data in text or json format.

The correct ways for you.

  1. Use <a></a> tag navigate to new page.

    <a href="/api/Redirect">Navigate to Google</a>
    
    [HttpPost]
    [Route("Redirect")]
    public async Task<IActionResult> Redirect()
    {
        var response = "https://google.com";
        return Redirect(response);
    }
    
  2. Get google url from controller.

    [HttpPost]
    [Route("Redirect")]
    public string Redirect()
    {
        var response = "https://google.com";
        return response;
    }
    
    $.ajax({
        url: "https://10.10.45.2/api/Redirect", 
        type: "POST",
        dataType: "text",
        success: function(data) {
            window.location = data;
        },
        error: function (jqXHR, timeout, message) {
        }
    });
    
Related