Reputation: 1727
I have a WebAPI. How can I return and open a Web page. For Example I want to open the CNN.com page.
[HttpGet]
public HttpResponseMessage Get()
{
//TODO: OPEN THE CNN.COM WEB PAGE
I have seen examples like this:
try {
var response = Request.CreateResponse(HttpStatusCode.Redirect); // tried MOVED too
response.Headers.Location = new Uri("cnn.com");
return response;
} catch (Exception e) {
ErrorSignal.FromCurrentContext().Raise(e);
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
But Request.CreateResponse is not an option in .Net Core 3
Any ideas? Thx in Advance
Upvotes: 4
Views: 11904
Reputation: 239440
Don't return HttpResponseMessage
. There's no need for that, and it just makes things more complicated than they need to be. Instead, return IActionResult
:
[HttpGet]
public IActionResult Get()
{
return Redirect("https://cnn.com");
}
I'd imagine your logic here is more complex, because having an API endpoint that does nothing but redirect to a totally different site makes no sense. Using IActionResult
as the return enables to you to return multiple different types of results. For example, you can do something like:
if (!ModelState.IsValid)
return BadRequest(ModelState);
// do something
return Ok();
Redirects don't make much sense, in general, in an API, because most clients that would interact with an API do not work like a web browser would. A redirect is actually a complete response. Web browsers take it upon themselves to automatically follow the URL in the Location
header of that response, so it's seamless to the end-user. However, most thin clients won't automatically follow redirects by default. The programmer utilizing your API must add code to detect that the redirect happened and then issue a new request for that new URL. Redirecting to something like the homepage of CNN makes even less sense, because the response wouldn't be something the programmer utilizing your API could really do anything with. They would never actually return the HTML coming from their response from like HttpClient
, for example, because it wouldn't work when not hosting actually on CNN.com. I know that was probably a contrived example, but it's worth mentioning in general. Response from APIs should be data, not things like HTML, as it doesn't make sense in an API context to receive HTML.
Upvotes: 9
Reputation: 6528
Posting it as an answer. Let me know if it works.
try {
var response = new HttpResponseMessage(HttpStatusCode.Redirect);
response.Headers.Location = new Uri("cnn.com");
return response;
} catch (Exception e) {
ErrorSignal.FromCurrentContext().Raise(e);
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
Upvotes: 3
Reputation: 753
try with this
var response = new HttpResponseMessage(HttpStatusCode.Redirect);
response.Headers.Location = new Uri("https://insight.xxx.com");
Upvotes: 2