【ASP.NET Web API2】利用HttpClient调用Web API(TODO)

参照: 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用

纯属记录一下遇到的问题:

我们利用HttpClient来调用自宿主方式寄宿的Web API。HttpClient定义在程序集“System.Net.Http.dll”中,还需要引用程序集“System.Net.Http.Formatting”,因为序列化请求和反序列化响应的相关类型定义在此程序集中,因为之前完全没有用过async&await 异步编程,于是跟着写了这样的一段代码

 static HttpClient httpClient = new HttpClient();
static void Main(string[] args)
{
Console.WriteLine("------------初识数据------------");
GetList();
Add(new Contact() { ID="004", Name="小米", PhoneNum="1380020000" });
Console.WriteLine("------------添加一个联系人后---------------");
GetList();
Console.Read();
} /// <summary>
/// 输出联系人列表
/// </summary>
private async static void GetList()
{
HttpResponseMessage response = await httpClient.GetAsync("http://127.0.0.1:7304/api/contacts");
List<Contact> contacts = await response.Content.ReadAsAsync<List<Contact>>();
foreach (var item in contacts)
{
Console.WriteLine("{0}-{1}-{2}", item.ID, item.Name, item.PhoneNum);
}
}
/// <summary>
/// 添加
/// </summary>
/// <param name="model"></param>
private async static void Add(Contact model)
{
await httpClient.PostAsJsonAsync<Contact>("http://127.0.0.1:7304/api/contacts", model);
}

运行后悲剧了,不是我预想的结果

 【ASP.NET Web API2】利用HttpClient调用Web API(TODO)

于是想了解一下async&await,找到很多相关文章、博客,实在是看不下去,看不懂,断点还每次跳的位置都不一样,也是醉了。于是先把async&await的问题放放

改了一下GetList()和Add();

       /// <summary>
/// 输出联系人列表
/// </summary>
private static void GetList()
{
HttpResponseMessage response = httpClient.GetAsync("http://127.0.0.1:7304/api/contacts").Result;
List<Contact> contacts = response.Content.ReadAsAsync<List<Contact>>().Result;
foreach (var item in contacts)
{
Console.WriteLine("{0}-{1}-{2}", item.ID, item.Name, item.PhoneNum);
}
}
/// <summary>
/// 添加
/// </summary>
/// <param name="model"></param>
private static void Add(Contact model)
{
HttpResponseMessage response= httpClient.PostAsJsonAsync<Contact>("http://127.0.0.1:7304/api/contacts", model).Result;
}

结果:

【ASP.NET Web API2】利用HttpClient调用Web API(TODO)

原因是数据初始化在构造函数中,每次调用API contacts都变回原来定义的那样(基础知识差到不忍直视==!)

        List<Contact> contacts;
public ContactsController()
{
contacts = new List<Contact>();
contacts.Add(new Contact() { ID = "001", Name = "小白", PhoneNum = "13529093839" });
contacts.Add(new Contact() { ID = "002", Name = "大白", PhoneNum = "13529093838" });
contacts.Add(new Contact() { ID = "003", Name = "小黑", PhoneNum = "13529088838" });
}

↑2015-04-11

上一篇:BZOJ 1087: [SCOI2005]互不侵犯King [状压DP]


下一篇:[NOIP2016]愤怒的小鸟 D2 T3 状压DP