久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

使用HttpClient消費ASP.NET Web API服務案例

瀏覽:37日期:2022-06-08 15:51:29

本篇體驗使用HttpClient消費ASP.NET Web API服務,例子比較簡單。

依次點擊"文件","新建","項目"。

選擇"ASP.NET Web API"項目。

在Models文件夾下創建Person.cs類。

    public class Person    {public int Id { get; set; }public string FirstName { get; set; }public string LastName { get; set; }    }

在Controllers文件夾下創建一個空的PersonController。

    public class PersonController : ApiController    {    }

創建一個符合管理的方法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

都可以獲取到數據。

在解決方案下創建一個控制臺應用程序。

在控制臺下引用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();    }}

把控制臺程序設置為啟動項。點擊"啟動"。

如果想獲取xml格式,可以設置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類中,把發出請求的信息封裝到HttpRequestMessage中。

在控制臺應用程序引用如下:

System.Net.Http.dll
System.Net.Http.Formatting.dll

編寫如下:

static void Main(string[] args){    Console.WriteLine("獲取ASP.NET Web API服務內容如下:");    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);}

以上就是創建簡單的ASP.NET Web API服務,以及使用WebClient和HttpClient消費服務的簡單例子。

到此這篇關于使用HttpClient消費ASP.NET Web API服務的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持。

標簽: ASP.NET
相關文章:
主站蜘蛛池模板: 平阴县| 正定县| 陆川县| 新巴尔虎左旗| 元江| 道真| 永和县| 文成县| 东明县| 镶黄旗| 清原| 灵山县| 集贤县| 衡水市| 华容县| 闻喜县| 姜堰市| 昆明市| 诸暨市| 辉县市| 永善县| 沈阳市| 古交市| 佳木斯市| 兴城市| 肇州县| 平陆县| 比如县| 尼勒克县| 库伦旗| 乌鲁木齐县| 宜兰县| 拜城县| 都兰县| 正安县| 佛冈县| 宁河县| 府谷县| 武城县| 镶黄旗| 黄冈市|