我有Web API项目,主持数据服务。一切都很好,我可以使用以下代码从控制台客户端使用它:
private static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:15017/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync("api/products");
if (response.IsSuccessStatusCode)
{
var products = await response.Content.ReadAsAsync<List<Product>>();
foreach (var product in products)
{
Console.WriteLine(product.Name);
Console.WriteLine(product.Description);
Console.WriteLine(product.ShortDescription);
Console.WriteLine(product.Prize);
Console.WriteLine("\n");
}
}
}
}
private static void Main(string[] args)
{
RunAsync().Wait();
}
完美无缺。
比我有windows phone 8 app。它有这样的结构,我有ViewModels,它创建IRepository接口的实例。我尝试使用与我的控制台应用程序中相同的代码连接到web api并从IRepository类加载数据但是当我尝试添加对System.Net.Http.Formatting的引用时,我得到了一个安装包的错误:
Adding 'Microsoft.AspNet.WebApi.WebHost 5.1.2' to PhoneApp.
Install-Package : Could not install package 'Microsoft.AspNet.WebApi.WebHost 5.1.2'. You are trying to install this package into a project that
targets 'WindowsPhone,Version=v8.0', but the package does not contain any assembly references or content files that are compatible with that
framework. For more information, contact the package author.
那么如何在我的Windows手机应用程序中使用web api?