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.
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
You can use HttpResponseMessage
instead, something like:
var response = new HttpResponseMessage(HttpStatusCode.Redirect);
response.Headers.Location = new Uri("https://insight.xxx.com");
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.