无法使用来自 Asp MVC 6 Web Api 的 HttpClient

Can not use HttpClient from Asp MVC 6 Web Api

我尝试编写简单的代码:

 public async Task<string> GetData(String labelName)
    {           
        using (var client = new HttpClient())
        {
            var uri = new Uri(@"https://example.com/over/search_field?=search_label=" + labelName);

            var response = await client.GetAsync(uri).ConfigureAwait(false);
            var textResult = await response.Content.ReadAsStringAsync();
            return textResult;
        }
    }

在project.json:

 {
"webroot": "wwwroot",
"version": "1.0.0-*",
"dependencies": {
  "Microsoft.AspNet.IISPlatformHandler": "1.0.0-beta8",
 "Microsoft.AspNet.Mvc": "6.0.0-beta8",
 "Microsoft.AspNet.Server.Kestrel": "1.0.0-beta8",
 "Microsoft.AspNet.StaticFiles": "1.0.0-beta8",

 "Microsoft.Framework.Logging": "1.0.0-beta8",
 "Microsoft.Framework.Logging.Console": "1.0.0-beta8",
 "Microsoft.Framework.Logging.Debug": "1.0.0-beta8",
 "Microsoft.Net.Http": "2.2.22"
  },      
 "frameworks": {
  "dnx451": {
    "dependencies": {
       "Microsoft.AspNet.WebApi.Client": "5.2.3",
      "Microsoft.AspNet.WebApi.Owin": "5.2.3",
      "System.Net.Http": "4.0.1-beta-23409"


   },
   "frameworkAssemblies": {
     "System.Net": "4.0.0.0",
     "System.Net.Http": "4.0.0.0"
   }
 },
 "dnxcore50": { }
},

但是,当我尝试构建代码时出现错误:

Error CS0246 The type or namespace name 'HttpClient' could not be found (are you missing a using directive or an assembly reference?)

你能帮帮我吗?如何修复此错误? 我使用 VS 2015 和 ASP MVC 6 Web API。 谢谢!

这对我有用。我将 System.Net.Http 添加到 dependencies 部分并构建了项目(因此在 DNX 4.5.1DNX Core 5.0 中恢复了这个新的依赖关系)

"dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final",
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    // Removed some dependencies for saving space:)
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final",
    "System.Net.Http": "4.0.1-beta-23409"
},
"frameworks": {
    "dnx451": { },
    "dnxcore50": {}
},

在以下运行时进行了验证,并且工作正常。

  • coreclr - X86 - 1.0.0-rc1-update1
  • coreclr - X64 - 1.0.0-rc1-update1
  • clr - X86 - 1.0.0-rc1-update1
  • clr - X64 - 1.0.0-rc1-update1

此外,您需要确保您有 using 指令,该指令在 class 文件中导入 System.Net.Http 命名空间,您有 GetData 方法。

using System.Net.Http;