“System.Net.Http.HttpContent”不包含“ReadAsAsync”的定义,并没有扩展方法并没有、不包含、定义、方法

2023-09-02 02:09:56 作者:让时间冲淡回忆

我做了一个控制台应用程序来消耗我只是做一个Web API。控制台应用程序code不能编译。它给我的编译错误:

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 Files文件微软ASP.NET ASP.NET MVC 4 组件文件夹

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.Http $库 System.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.

反光来营救!