ASP.NET延遲調(diào)用或多次調(diào)用第三方Web API服務(wù)
本篇體驗使用HttpClient消費ASP.NET Web API服務(wù),例子比較簡單。
依次點擊"文件","新建","項目"。
選擇"ASP.NET Web API"項目。
在Models文件夾下創(chuàng)建Person.cs類。
public class Person {public int Id { get; set; }public string FirstName { get; set; }public string LastName { get; set; } }在Controllers文件夾下創(chuàng)建一個空的PersonController。
public class PersonController : ApiController { }創(chuàng)建一個符合管理的方法GetAllPersons。
public class PersonController : ApiController {public IEnumerable<Person> GetAllPersons(){ return new List<Person> {new Person(){Id = 1, FirstName = "jack", LastName = "li"},new Person(){Id = 2, FirstName = "darren", LastName = "ji"},new Person(){Id = 3, FirstName = "sunny", LastName = "su"} };} }在瀏覽器中輸入:
http://localhost:2497/api/Person
http://localhost:2497/api/Person/AllPersons
都可以獲取到數(shù)據(jù)。
在解決方案下創(chuàng)建一個控制臺應(yīng)用程序。
在控制臺下引用System.Net,并編寫如下:
static void Main(string[] args){ using (WebClient proxy = new WebClient()) {var response = proxy.DownloadString("http://localhost:2497/api/Person");Console.WriteLine(response);Console.ReadKey(); }}把控制臺程序設(shè)置為啟動項。點擊"啟動"。

如果想獲取xml格式,可以設(shè)置WebClient的Headers屬性。
代碼修改如下:
static void Main(string[] args){ using (WebClient proxy = new WebClient()) {proxy.Headers.Add(HttpRequestHeader.Accept, "application/xml");var response = proxy.DownloadString("http://localhost:2497/api/Person");Console.WriteLine(response);Console.ReadKey(); }}
WebClient用起來似乎也不錯,不過,HttpClient具有更豐富的API。HttpClient把接收的信息封裝在HttpResponseMessage類中,把發(fā)出請求的信息封裝到HttpRequestMessage中。
在控制臺應(yīng)用程序引用如下:
System.Net.Http.dll
System.Net.Http.Formatting.dll
編寫如下:
static void Main(string[] args){ Console.WriteLine("獲取ASP.NET Web API服務(wù)內(nèi)容如下:"); HttpClient proxy = new HttpClient(); proxy.GetAsync("http://localhost:2497/api/Person").ContinueWith((previous) => {HttpResponseMessage response = previous.Result;response.Content.ReadAsStringAsync().ContinueWith((a) =>{ foreach (var item in a.Result) {Console.WriteLine(item.ToString()); }}); }); Console.ReadKey(true);}以上就是創(chuàng)建簡單的ASP.NET Web API服務(wù),以及使用WebClient和HttpClient消費服務(wù)的簡單例子。
到此這篇關(guān)于ASP.NET延遲調(diào)用或多次調(diào)用第三方Web API服務(wù)的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持。
相關(guān)文章:
1. 如何將asp.net core程序部署到Linux服務(wù)器2. ASP.NET MVC前臺動態(tài)添加文本框并在后臺使用FormCollection接收值3. ASP.NET MVC獲取多級類別組合下的產(chǎn)品4. 使用HttpClient增刪改查ASP.NET Web API服務(wù)5. Asp.net Core項目配置HTTPS支持6. ASP.NET堆和棧三之引用類型對象拷貝和內(nèi)存分配7. 如何使用ASP.NET Core 配置文件8. ASP.Net Core對USB攝像頭進(jìn)行截圖9. ASP.NET MVC實現(xiàn)單個圖片上傳、限制圖片格式與大小并在服務(wù)端裁剪圖片10. asp.net生成HTML

網(wǎng)公網(wǎng)安備