我制作了一个控制台应用程序来使用我刚刚制作的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客户端使用它。
发布于 2013-01-25 19:26:30
确保您已在控制台应用程序中安装了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
发布于 2016-02-05 21:59:39
添加对System.Net.Http.Formatting.dll的引用可能会导致DLL不匹配问题。目前,System.Net.Http.Formatting.dll似乎引用了Newtonsoft.Json.DLL的4.5.0.0版本,而最新版本是6.0.0.0。这意味着如果您引用最新的Newtonsoft NuGet包或动态链接库,您还需要添加绑定重定向以避免.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;
}
}
发布于 2013-10-24 21:31:12
或者,如果您使用的是VS2012,您可以转到包管理器控制台并输入Install-Package Microsoft.AspNet.WebApi.Client
这将下载最新版本的程序包
https://stackoverflow.com/questions/14520762
复制相似问题