Search code examples
asp.netjsonasp.net-mvcdotnet-httpclient

ASP.NET MVC Controller Method GET to external API


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; }
}

Solution

  • Why is it that when I ask a question 10 minutes later I come up with the answer so here it is if anyone is interested.

    This seems to be the most elegant solution I can come up with but if anyone has any improvements please let me know thanks.

    [HttpGet]
        public async Task<ActionResult> GetCustomers()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                HttpResponseMessage response = await client.GetAsync(customerApi);
                if (response.IsSuccessStatusCode)
                {
                    string jsondata = await response.Content.ReadAsStringAsync();
                    return Content(jsondata, "application/json");
                }
                return Json(1, JsonRequestBehavior.AllowGet);
            }
        }