0

In ASP.NET Core 3, what is the best way to call a Web API that I trust from my site (server-side) and pass through its response on my site?

For example, I have a controller action such as this, and I want to just get whatever HTTP status and JSON data, etc. comes out of the call.

[HttpGet]
public async Task<IActionResult> Get(int id){
   string url = "https://...";
   return await httpClient.GetAsync(url);  // not quite right...
}

However, GetAsync returns an HttpResponseMessage. Should I convert this to a IActionResult? If so, how can I do so without resorting to System.Web.Http.ResponseMessageResult from Microsoft.AspNetCore.WebApiCompatShim (since I don't need compatibility with older web API conventions)? I feel like there's a simpler approach I'm missing.

(I'd like the method here with the least overhead, of course, since I'm not seeking to transform or augment the response. No deserialization, especially.)

Patrick Szalapski
  • 7,020
  • 9
  • 49
  • 98

2 Answers2

1

The easiest thing you can do is just return the string result. With this aproach you will need to parse the Json string on the client side.

[HttpGet]
public async Task<IActionResult> Get(int id){
   string url = "https://...";
   return await httpClient.GetStringAsync(url);
}

If you want to return a json object you will have to model bind it afaik.

[HttpGet]
public async Task<MyType> Get(int id){
   string url = "https://...";
   var content = await httpClient.GetStringAsync(url);
   // this is Newtonsoft.Json, use the System.Text.Json if you are on .net core 3.*
   return JsonConvert.DeserializeObject<MyType>(content);
}
Anton Toshik
  • 1,881
  • 2
  • 14
  • 33
1

You could try:

[HttpGet]
public async Task<IActionResult> Get()
{
    HttpClient httpClient = new HttpClient();
    string url = "http://localhost:...";
    var response =   httpClient.GetAsync(url).Result;
    var statusCode = response.StatusCode;
    string responseBody = await response.Content.ReadAsStringAsync();
    return Ok(new { StatusCode = statusCode,ResponseBody = responseBody});
}
Rena
  • 14,556
  • 3
  • 15
  • 44