“System.Net.Http.HttpContent"不包含“ReadAsAsync"的定义,也没有扩展方法 [英] 'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

查看:36
本文介绍了“System.Net.Http.HttpContent"不包含“ReadAsAsync"的定义,也没有扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个控制台应用程序来使用我刚刚制作的 Web API.控制台应用程序代码无法编译.它给了我编译错误:

I made a console app to consume a Web API I just made. The console app code does not compile. It gives me the compilation error:

'System.Net.Http.HttpContent' does not contain a definition for 
'ReadAsAsync' and no extension method 'ReadAsAsync' accepting a 
first argument of type 'System.Net.Http.HttpContent' could be 
found (are you missing a using directive or an assembly reference?)

这是发生此错误的测试方法.

Here's a test method in which this error occurs.

static IEnumerable<Foo> GetAllFoos()
{
  using (HttpClient client = new HttpClient())
  {
    client.DefaultRequestHeaders.Add("appkey", "myapp_key");

    var response = client.GetAsync("http://localhost:57163/api/foo").Result;

    if (response.IsSuccessStatusCode)
      return response.Content.ReadAsAsync<IEnumerable<Foo>>().Result.ToList();
  }

  return null;
}

我使用过这种方法并从 MVC 客户端使用它.

I have used this method and consumed it from an MVC client.

推荐答案

经过长时间的挣扎,我找到了解决方案.

After a long struggle, I found the solution.

解决方案:添加对System.Net.Http.Formatting.dll的引用.此程序集也位于 C:Program FilesMicrosoft ASP.NETASP.NET MVC 4Assemblies 文件夹中.

Solution: Add a reference to System.Net.Http.Formatting.dll. This assembly is also available in the C:Program FilesMicrosoft ASP.NETASP.NET MVC 4Assemblies folder.

方法ReadAsAsync是在类HttpContentExtensions中声明的扩展方法,该类位于库中的命名空间System.Net.HttpSystem.Net.Http.Formatting.

The method ReadAsAsync is an extension method declared in the class HttpContentExtensions, which is in the namespace System.Net.Http in the library System.Net.Http.Formatting.

反射器来拯救了!

这篇关于“System.Net.Http.HttpContent"不包含“ReadAsAsync"的定义,也没有扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆