ASP.NET MVC控制器方法GET到外部API

时间:2016-11-17 01:55:44

标签: asp.net json asp.net-mvc api httpclient

我有一个托管在不同域上的外部api现在我们可以使用以下url作为示例

https://myapi.mydomain/api/data

此API返回以下数据

{"data":[
    {
        "id":1,
        "company":"JUST A DEMO",
        "ext_identifier":"DEMO1"
    },
    {
        "id":2,
        "company":"ANOTHER DEMO",
        "ext_identifier":"DEMO2"
    }
 ]}

我需要调用一个控制器方法来对这个API执行GET请求,然后返回JSON数据供我使用。

到目前为止,我有以下代码,我想我很接近......

这是控制器代码

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

1 个答案:

答案 0 :(得分:1)

为什么当我在10分钟后提出问题时,我想出了答案,所以在这里,如果有人有兴趣的话。

这似乎是我能提出的最优雅的解决方案,但如果有任何改进,请让我知道谢谢。

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