【问题标题】:ASP.NET MVC Controller Method GET to external APIASP.NET MVC 控制器方法 GET 到外部 API
【发布时间】:2017-03-31 10:32:21
【问题描述】:

我有一个托管在不同域上的外部 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; }
}

【问题讨论】:

  • 问题陈述是什么?
  • 抱歉,我只是没有取回任何数据,看起来它在 ReadAsAsync 行上失败了
  • 你想在你的 MVC 控制器中读取 json 数据吗?

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


【解决方案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);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多