Web API redirect to web page

14,807

Solution 1

The syntax has changed in ASP.Net-Core. HttpResponseMessage is no longer used in action results. They will serialized like any other model returned object.

Use instead, the Controller.Redirect method which returns a RedirectResult

public IActionResult Get() {
    return Redirect("https://xxx.xxxx.com");
}

RedirectResult

RedirectResult will redirect us to the provided URL, it doesn’t matter if the URL is relative or absolute, it just redirect, very simple. Other thing to note is that it can redirect us temporarily which we’ll get 302 status code or redirect us permanently which we’ll get 301 status code. If we call the Redirect method, it redirect us temporarily...

Reference Asp.Net Core Action Results Explained

Solution 2

That's what the Redirect() method exactly does:

return Redirect("https://xxx.xxx.com");

But if you want more control, you can return a ContentResult:

response.Headers.Location = new Uri("https://xxx.xxx.com");
return new ContentResult {
  StatusCode = (int)HttpStatusCode.Redirect,
  Content = "Check this URL"
};

I don't see any benefit for doing this, though. Well, unless if you use some client that will not follow the redirect and you want to provide some instructions or content in the Content property, which the client will see as the body of the returned page.

Solution 3

You can use HttpResponseMessage instead, something like:

 var response = new HttpResponseMessage(HttpStatusCode.Redirect);
 response.Headers.Location = new Uri("https://insight.xxx.com");
Share:
14,807
Tim
Author by

Tim

Updated on June 12, 2022

Comments

  • Tim
    Tim almost 2 years

    I have a Web API that I need to convert to API Core 2. I have one issue I cannot seem to resolve. There is a redirect in the controller that uses Request.CreateResponse which does not appear to be available in .Net Core?

    public HttpResponseMessage Get() {
        var response = Request.CreateResponse(HttpStatusCode.Redirect);
        response.Headers.Location = new Uri("https://xxx.xxxx.com");
        return response;
    }
    

    Any idea how I can modify this to work? Basically if a user does not pass any parameters, we just send them to a web page.