Asp.net
“System.Net.Http.HttpContent”不包含“ReadAsAsync”的定義,也沒有擴展方法
我製作了一個控制台應用程序來使用我剛剛製作的 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 客戶端使用它。
經過長時間的鬥爭,我找到了解決辦法。
解決方案:添加對
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反光板來救場了!