日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

使用HttpClient消费ASP.NET Web API服务

發(fā)布時間:2023/12/15 asp.net 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用HttpClient消费ASP.NET Web API服务 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

本篇體驗(yàn)使用HttpClient消費(fèi)ASP.NET Web API服務(wù),例子比較簡單。

?

依次點(diǎn)擊"文件","新建","項(xiàng)目"。

?

選擇"ASP.NET Web API"項(xiàng)目。

?

在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è)置為啟動項(xiàng)。點(diǎn)擊"啟動"。

?

?

如果想獲取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消費(fèi)服務(wù)的簡單例子。

總結(jié)

以上是生活随笔為你收集整理的使用HttpClient消费ASP.NET Web API服务的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。