【问题标题】:How to perform a request to a REST API in ASP.net 5.0 (MVC6)如何在 ASP.net 5.0 (MVC6) 中执行对 REST API 的请求
【发布时间】:2015-06-17 14:16:20
【问题描述】:

我正在使用 Visual Studio 2015 RC 编写一个 ASP.Net 5、MVC 6 应用程序(也称为“ASP.net vNext”)。

如何对 REST API 执行简单的 GET 请求?在 .net 4.5 中,我会使用 HttpClient,但它似乎不再可用。

我已尝试按照 Visual Studio 的建议添加“System.Net.Http”和“Microsoft.Net.Http”包,但是我仍然得到“找不到类型或命名空间名称 'HttpClient'”让我相信 HttpClient 不是在 ASP.net 5 中执行此操作的正确方法?

谁能建议在 ASP.net 5 中发出 HTTP GET 请求的正确方法?

更新:我的问题不是“找不到 ASP.NET 5.0 中的 HttpClient?”的重复项?因为给出的答案已过时,不适用于最新版本的 ASP.net 5.0

【问题讨论】:

  • HttpClientHandler 呢?
  • 你的意思是 ASP.NET 5 和 MVC 6 吗?
  • 之前好像是别人asked this question
  • 我已更新为引用 MVC6,谢谢。 “找不到 ASP.NET 5.0 中的 HttpClient?”中的步骤?可悲的是没有为我工作。

标签: asp.net-mvc asp.net-core dotnet-httpclient


【解决方案1】:

这里有一个解决方案,我刚刚在 ASP.Net 5 网站项目模板上尝试过。在 HomeController 中添加如下方法

static async Task<string> DownloadPageAsync()
    {
        string page = "http://en.wikipedia.org/";

        using (HttpClient client = new HttpClient())
        using (HttpResponseMessage response = await client.GetAsync(page))
        using (HttpContent content = response.Content)
        {
            string result = await content.ReadAsStringAsync();

            return result.Substring(0, 50);
        }

    }

然后在 HomeControllers Index 方法中

string test = DownloadPageAsync().Result;

在 project.json 中,我在依赖项中添加了以下参考

  "Microsoft.Net.Http": "2.2.22"

【讨论】:

  • 嗨,马格努斯,谢谢。如果您正确设置了 nuget,则此代码有效,这是问题的症结所在。在这个线程上查看我的最新答案
【解决方案2】:

我找到了一个答案,部分来自名为“ 没有找到 ASP.NET 5.0 中的 HttpClient?',但是由于技术现在已经有了一些进步,因此存在一些缺失的空白。我在这里写了完整的解决方案:http://blogs.msdn.com/b/martinkearn/archive/2015/06/17/using-httpclient-with-asp-net-5-0.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    相关资源
    最近更新 更多