使用HttpClient增刪改查ASP.NET Web API服務(wù)
本篇體驗(yàn)使用HttpClient對(duì)ASP.NET Web API服務(wù)實(shí)現(xiàn)增刪改查。
創(chuàng)建ASP.NET Web API項(xiàng)目
新建項(xiàng)目,選擇"ASP.NET MVC 4 Web應(yīng)用程序"。
選擇"Web API"。
在Models文件夾下創(chuàng)建Product類。
public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } }
在Models文件夾下創(chuàng)建IProductRepository接口。
public interface IProductRepository { IEnumerable<Product> GetAll(); Product Get(int id); Product Add(Product item); void Remove(int id); bool Update(Product item); }
在Models文件夾下創(chuàng)建ProductRepository類,實(shí)現(xiàn)IProductRepository接口。
public class ProductRepository : IProductRepository { private List<Product> products = new List<Product>(); private int _nextId = 1; public ProductRepository() { Add(new Product() {Name = "product1", Category = "sports", Price = 88M}); Add(new Product() { Name = "product2", Category = "sports", Price = 98M }); Add(new Product() { Name = "product3", Category = "toys", Price = 58M }); } public IEnumerable<Product> GetAll() { return products; } public Product Get(int id) { return products.Find(p => p.Id == id); } public Product Add(Product item) { if (item == null) { throw new ArgumentNullException("item"); } item.Id = _nextId++; products.Add(item); return item; } public bool Update(Product item) { if (item == null) { throw new ArgumentNullException("item"); } int index = products.FindIndex(p => p.Id == item.Id); if (index == -1) { return false; } products.RemoveAt(index); products.Add(item); return true; } public void Remove(int id) { products.RemoveAll(p => p.Id == id); } }
在Controllers文件夾下創(chuàng)建空的ProductController。
public class ProductController : ApiController { static readonly IProductRepository repository = new ProductRepository(); //獲取所有 public IEnumerable<Product> GetAllProducts() { return repository.GetAll(); } //根據(jù)id獲取 public Product GetProduct(int id) { Product item = repository.Get(id); if (item == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return item; } //根據(jù)類別查找所有產(chǎn)品 public IEnumerable<Product> GetProductsByCategory(string category) { return repository.GetAll().Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase)); } //創(chuàng)建產(chǎn)品 public HttpResponseMessage PostProduct(Product item) { item = repository.Add(item); var response = Request.CreateResponse(HttpStatusCode.Created, item); string uri = Url.Link("DefaultApi", new {id = item.Id}); response.Headers.Location = new Uri(uri); return response; } //更新產(chǎn)品 public void PutProduct(int id, Product product) { product.Id = id; if (!repository.Update(product)) { throw new HttpResponseException(HttpStatusCode.NotFound); } } //刪除產(chǎn)品 public void DeleteProduct(int id) { Product item = repository.Get(id); if (item == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } repository.Remove(id); } }
在瀏覽器中輸入:
http://localhost:1310/api/Product 獲取到所有產(chǎn)品
http://localhost:1310/api/Product/1 獲取編號(hào)為1的產(chǎn)品
使用HttpClient查詢某個(gè)產(chǎn)品
在同一個(gè)解決方案下創(chuàng)建一個(gè)控制臺(tái)程序。
依次點(diǎn)擊"工具","庫(kù)程序包管理器","程序包管理器控制臺(tái)",輸入如下:
Install-Package Microsoft.AspNet.WebApi.Client
在控制臺(tái)程序下添加Product類,與ASP.NET Web API中的對(duì)應(yīng)。
public class Product { public string Name { get; set; } public double Price { get; set; } public string Category { get; set; } }
編寫如下:
static void Main(string[] args) { RunAsync().Wait(); Console.ReadKey(); } static async Task RunAsync() { using (var client = new HttpClient()) { //設(shè)置 client.BaseAddress = new Uri("http://localhost:1310/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //異步獲取數(shù)據(jù) HttpResponseMessage response = await client.GetAsync("/api/Product/1"); if (response.IsSuccessStatusCode) { Product product = await response.Content.ReadAsAsync<Product>(); Console.WriteLine("{0}\t{1}元\t{2}",product.Name, product.Price, product.Category); } } }
把控制臺(tái)項(xiàng)目設(shè)置為啟動(dòng)項(xiàng)目。
HttpResponseMessage的IsSuccessStatusCode只能返回true或false,如果想讓響應(yīng)拋出異常,需要使用EnsureSuccessStatusCode方法。
try { HttpResponseMessage response = await client.GetAsync("/api/Product/1"); response.EnsureSuccessStatusCode();//此方法確保響應(yīng)失敗拋出異常 } catch(HttpRequestException ex) { //處理異常 }
另外,ReadAsAsync方法,默認(rèn)接收MediaTypeFormatter類型的參數(shù),支持 JSON, XML, 和Form-url-encoded格式,如果想自定義MediaTypeFormatter格式,參照如下:
var formatters = new List<MediaTypeFormatter>() { new MyCustomFormatter(), new JsonMediaTypeFormatter(), new XmlMediaTypeFormatter() }; resp.Content.ReadAsAsync<IEnumerable<Product>>(formatters);
使用HttpClient查詢所有產(chǎn)品
static void Main(string[] args) { RunAsync().Wait(); Console.ReadKey(); } static async Task RunAsync() { using (var client = new HttpClient()) { //設(shè)置 client.BaseAddress = new Uri("http://localhost:1310/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //異步獲取數(shù)據(jù) HttpResponseMessage response = await client.GetAsync("/api/Product"); if (response.IsSuccessStatusCode) { IEnumerable<Product> products = await response.Content.ReadAsAsync<IEnumerable<Product>>(); foreach (var item in products) { Console.WriteLine("{0}\t{1}元\t{2}", item.Name, item.Price, item.Category); } } } }
使用HttpClient添加
static void Main(string[] args) { RunAsync().Wait(); Console.ReadKey(); } static async Task RunAsync() { using (var client = new HttpClient()) { //設(shè)置 client.BaseAddress = new Uri("http://localhost:1310/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //添加 var myProduct = new Product() { Name = "myproduct", Price = 88, Category = "other" }; HttpResponseMessage response = await client.PostAsJsonAsync("api/Product", myProduct); //異步獲取數(shù)據(jù) response = await client.GetAsync("/api/Product"); if (response.IsSuccessStatusCode) { IEnumerable<Product> products = await response.Content.ReadAsAsync<IEnumerable<Product>>(); foreach (var item in products) { Console.WriteLine("{0}\t{1}元\t{2}", item.Name, item.Price, item.Category); } } } }
使用HttpClient修改
static void Main(string[] args) { RunAsync().Wait(); Console.ReadKey(); } static async Task RunAsync() { using (var client = new HttpClient()) { //設(shè)置 client.BaseAddress = new Uri("http://localhost:1310/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //添加 HTTP POST var myProduct = new Product() { Name = "myproduct", Price = 100, Category = "other" }; HttpResponseMessage response = await client.PostAsJsonAsync("api/product", myProduct); if (response.IsSuccessStatusCode) { Uri pUrl = response.Headers.Location; //修改 HTTP PUT myProduct.Price = 80; // Update price response = await client.PutAsJsonAsync(pUrl, myProduct); } //異步獲取數(shù)據(jù) response = await client.GetAsync("/api/Product"); if (response.IsSuccessStatusCode) { IEnumerable<Product> products = await response.Content.ReadAsAsync<IEnumerable<Product>>(); foreach (var item in products) { Console.WriteLine("{0}\t{1}元\t{2}", item.Name, item.Price, item.Category); } } } }
使用HttpClient刪除
static void Main(string[] args) { RunAsync().Wait(); Console.ReadKey(); } static async Task RunAsync() { using (var client = new HttpClient()) { //設(shè)置 client.BaseAddress = new Uri("http://localhost:1310/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //添加 HTTP POST var myProduct = new Product() { Name = "myproduct", Price = 100, Category = "other" }; HttpResponseMessage response = await client.PostAsJsonAsync("api/product", myProduct); if (response.IsSuccessStatusCode) { Uri pUrl = response.Headers.Location; //修改 HTTP PUT myProduct.Price = 80; // Update price response = await client.PutAsJsonAsync(pUrl, myProduct); //刪除 HTTP DELETE response = await client.DeleteAsync(pUrl); } //異步獲取數(shù)據(jù) response = await client.GetAsync("/api/Product"); if (response.IsSuccessStatusCode) { IEnumerable<Product> products = await response.Content.ReadAsAsync<IEnumerable<Product>>(); foreach (var item in products) { Console.WriteLine("{0}\t{1}元\t{2}", item.Name, item.Price, item.Category); } } } }
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
相關(guān)文章
.NET CORE動(dòng)態(tài)調(diào)用泛型方法詳解
這篇文章主要為大家詳細(xì)介紹了.NET CORE動(dòng)態(tài)調(diào)用泛型方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08ASP.NET動(dòng)態(tài)生成靜態(tài)頁(yè)面的實(shí)例代碼
生成靜態(tài)頁(yè)有很多好處,可以緩解服務(wù)器壓力、方便搜索網(wǎng)站搜索等等,下面介紹一下生成靜態(tài)頁(yè)的實(shí)例代碼,有需要的朋友可以參考一下2013-07-07ASP.NET中Dictionary基本用法實(shí)例分析
這篇文章主要介紹了ASP.NET中Dictionary基本用法,結(jié)合實(shí)例形式分析了Dictionary的基本功能、使用步驟與相關(guān)操作技巧,需要的朋友可以參考下2016-08-08Hangfire在ASP.NET CORE中的簡(jiǎn)單實(shí)現(xiàn)方法
下面小編就為大家分享一篇Hangfire在ASP.NET CORE中的簡(jiǎn)單實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2017-11-11詳解ASP.NET 生成二維碼實(shí)例(采用ThoughtWorks.QRCode和QrCode.Net兩種方式)
本篇文章主要介紹了ASP.NET 生成二維碼實(shí)例,使用了兩種方法,包括ThoughtWorks.QRCode和QrCode.Net,具有一定的參考價(jià)值,有興趣的可以了解一下。2016-12-12淺析Repeater控件的使用 (原樣導(dǎo)出和動(dòng)態(tài)顯示/隱藏Repeater中的列)
本文主要介紹了淺析Repeater控件的使用 (原樣導(dǎo)出和動(dòng)態(tài)顯示/隱藏Repeater中的列)的具體方法,需要的朋友可以看下2016-12-12MVC4制作網(wǎng)站教程第四章 前臺(tái)欄目瀏覽4.5
這篇文章主要為大家詳細(xì)介紹了MVC4制作網(wǎng)站教程,前臺(tái)欄目瀏覽功能實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08基于asp.net實(shí)現(xiàn)圖片在線上傳并在線裁剪功能
本文主要介紹了基于asp.net實(shí)現(xiàn)圖片在線上傳并在線裁剪功能的具體事例代碼,具有一定的參考價(jià)值。需要的朋友可以參考下2016-12-12一個(gè)伴隨ASP.NET從1.0到4.0的OutputCache Bug介紹
一個(gè)伴隨ASP.NET從1.0到4.0的OutputCache Bug介紹,學(xué)習(xí).net的朋友可以參考下。2011-11-11一個(gè)基于Asp.Net MVC的權(quán)限方案
最近這段時(shí)間博客園有幾位同學(xué)在探討通用的權(quán)限方案,偶閑來(lái)無(wú)事,也來(lái)湊湊熱鬧,下面簡(jiǎn)單說(shuō)一下我的簡(jiǎn)單解決方案,基于AOP的。由于使用了Asp.Net MVC 開發(fā),可能需要先對(duì)MVC有些了解,思路都是差不多的。2010-02-02