I have an external API that is hosted on a different domain for now we can use the following URL as an example
https://myapi.mydomain/api/data
This API returns the following data:
{"data":[
{
"id":1,
"company":"JUST A DEMO",
"ext_identifier":"DEMO1"
},
{
"id":2,
"company":"ANOTHER DEMO",
"ext_identifier":"DEMO2"
}
]}
I need to call a controller method that does the GET request against this API and then returns the JSON data for me to consume.
So far I have the following code, I think I am close....
Here is the controller code
string url = "https://myapi.mydomain/";
[HttpGet]
public async Task<ActionResult> Search()
{
CustomerList customers = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// New code:
HttpResponseMessage response = await client.GetAsync("api/data");
if (response.IsSuccessStatusCode)
{
customers = await response.Content.ReadAsAsync<CustomerList>();
}
}
return Json(new
{
data = customers
},
JsonRequestBehavior.AllowGet);
}
public class CustomerList
{
public int id { get; set; }
public string company { get; set; }
public string ext_identifier { get; set; }
}