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.
redirect() The redirect() method of the Response interface returns a Response resulting in a redirect to the specified URL. Note: This is mainly relevant to the ServiceWorker API. A controlling service worker could intercept a page's request and redirect it as desired.
In response to a REST API request, the Nest API server returns a redirect. The REST client detects the redirect and requests the page that the client was redirected to. Some HTTP implementations do not forward the Authorization header to the redirected URI, and this results in a 401 Unauthorized error.
You can either (a) redirect the HTTP header from the . htaccess (a header redirect from PHP code will not carry the POST), or you can use some simple curl code to re-port to the new page in your PHP code.
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
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.
You can use HttpResponseMessage
instead, something like:
var response = new HttpResponseMessage(HttpStatusCode.Redirect);
response.Headers.Location = new Uri("https://insight.xxx.com");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With