当前位置:  开发笔记 > 编程语言 > 正文

不能使用Asp MVC 6 Web Api的HttpClient

如何解决《不能使用AspMVC6WebApi的HttpClient》经验,为你挑选了1个好方法。

我尝试编写简单的代码:

 public async Task 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": { }
},

但是,当我尝试构建代码时,我得到错误:

错误CS0246找不到类型或命名空间名称'HttpClient'(您是否缺少using指令或程序集引用?)

你能帮助我吗?如何解决这个错误?我使用VS 2015和ASP MVC 6 Web API.谢谢!



1> Shyju..:

这对我有用.我添加System.Net.Httpdependencies部分,建成项目(因此恢复了这两个新的依赖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在您拥有GetData方法的类文件中导入System.Net.Http命名空间的指令.

using System.Net.Http;

推荐阅读
李桂平2402851397
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有