Wat*_* v2 87 .net asp.net asp.net-mvc asp.net-web-api
我制作了一个控制台应用程序来使用我刚刚制作的Web API.控制台应用程序代码无法编译.它给了我编译错误:
'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?)
这是一种发生此错误的测试方法.
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客户端使用它.
Wat*_* v2 122
经过长期的斗争,我找到了解决方案.
解决方案:添加引用System.Net.Http.Formatting.dll.此程序集也可在C:\ Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies文件夹中找到.
该方法ReadAsAsync是在类中声明的扩展方法HttpContentExtensions,该方法位于System.Net.Http库的名称空间中System.Net.Http.Formatting.
反射器来救援!
Dar*_*rov 87
确保已correct NuGet package在控制台应用程序中安装:
<package id="Microsoft.AspNet.WebApi.Client" version="4.0.20710.0" />
而且你的目标是至少.NET 4.0.
这就是说,你的GetAllFoos函数被定义为IEnumerable<Prospect>在你的ReadAsAsync方法中返回一个你通过IEnumerable<Foo>哪个显然不兼容的类型.
Install-Package Microsoft.AspNet.WebApi.Client
小智 14
尝试使用此
 程序包管理器控制台
Install-Package System.Net.Http.Formatting.Extension -Version 5.2.3,然后使用添加引用进行添加。
小智 11
添加对System.Net.Http.Formatting.dll的引用可能会导致DLL不匹配问题.目前,System.Net.Http.Formatting.dll似乎引用了Newtonsoft.Json.DLL的4.5.0.0版,而最新版本是6.0.0.0.这意味着如果您引用最新的Newtonsoft NuGet包或DLL,您还需要添加绑定重定向以避免.NET程序集异常:
<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
 </dependentAssembly> 
因此,添加对System.Net.Http.Formatting.dll的引用的替代解决方案是将响应作为字符串读取,然后使用JsonConvert.DeserializeObject(responseAsString)自行解决.完整的方法是:
public async Task<T> GetHttpResponseContentAsType(string baseUrl, string subUrl)
{
     using (var client = new HttpClient())
     {
         client.BaseAddress = new Uri(baseUrl);
         client.DefaultRequestHeaders.Accept.Clear();
         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
         HttpResponseMessage response = await client.GetAsync(subUrl);
         response.EnsureSuccessStatusCode();
         var responseAsString = await response.Content.ReadAsStringAsync();
         var responseAsConcreteType = JsonConvert.DeserializeObject<T>(responseAsString);
         return responseAsConcreteType;
      }
}
| 归档时间: | 
 | 
| 查看次数: | 86029 次 | 
| 最近记录: |