使用HttpClient对ASP.NET Web API服务实现增删改查
来源:互联网 发布:易语言mysql数据库 编辑:程序博客网 时间:2024/05/22 03:50
本篇体验使用HttpClient对ASP.NET Web API服务实现增删改查。
创建ASP.NET Web API项目
新建项目,选择"ASP.NET MVC 4 Web应用程序"。
选择"Web API"。
在Models文件夹下创建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文件夹下创建IProductRepository接口。
public interface IProductRepository{IEnumerable<Product> GetAll();Product Get(int id);Product Add(Product item);void Remove(int id);bool Update(Product item);}
在Models文件夹下创建ProductRepository类,实现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文件夹下创建空的ProductController。
public class ProductController : ApiController{static readonly IProductRepository repository = new ProductRepository();//获取所有public IEnumerable<Product> GetAllProducts(){return repository.GetAll();}//根据id获取public Product GetProduct(int id){Product item = repository.Get(id);if (item == null){throw new HttpResponseException(HttpStatusCode.NotFound);}return item;}//根据类别查找所有产品public IEnumerable<Product> GetProductsByCategory(string category){returnrepository.GetAll().Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));}//创建产品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;}//更新产品public void PutProduct(int id, Product product){product.Id = id;if (!repository.Update(product)){throw new HttpResponseException(HttpStatusCode.NotFound);}}//删除产品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 获取到所有产品
http://localhost:1310/api/Product/1 获取编号为1的产品
使用HttpClient查询某个产品
在同一个解决方案下创建一个控制台程序。
依次点击"工具","库程序包管理器","程序包管理器控制台",输入如下:
Install-Package Microsoft.AspNet.WebApi.Client
在控制台程序下添加Product类,与ASP.NET Web API中的对应。
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()){//设置client.BaseAddress = new Uri("http://localhost:1310/");client.DefaultRequestHeaders.Accept.Clear();client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//异步获取数据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);}}}
把控制台项目设置为启动项目。
HttpResponseMessage的IsSuccessStatusCode只能返回true或false,如果想让响应抛出异常,需要使用EnsureSuccessStatusCode方法。
try{HttpResponseMessage response = await client.GetAsync("/api/Product/1");response.EnsureSuccessStatusCode();//此方法确保响应失败抛出异常}catch(HttpRequestException ex){//处理异常}
另外,ReadAsAsync方法,默认接收MediaTypeFormatter类型的参数,支持 JSON, XML, 和Form-url-encoded格式,如果想自定义MediaTypeFormatter格式,参照如下:
var formatters = new List<MediaTypeFormatter>() {new MyCustomFormatter(),new JsonMediaTypeFormatter(),new XmlMediaTypeFormatter()};resp.Content.ReadAsAsync<IEnumerable<Product>>(formatters);
使用HttpClient查询所有产品
static void Main(string[] args){RunAsync().Wait();Console.ReadKey();}static async Task RunAsync(){using (var client = new HttpClient()){//设置client.BaseAddress = new Uri("http://localhost:1310/");client.DefaultRequestHeaders.Accept.Clear();client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//异步获取数据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()){//设置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);//异步获取数据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()){//设置client.BaseAddress = new Uri("http://localhost:1310/");client.DefaultRequestHeaders.Accept.Clear();client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//添加 HTTP POSTvar 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 PUTmyProduct.Price = 80; // Update priceresponse = await client.PutAsJsonAsync(pUrl, myProduct);}//异步获取数据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()){//设置client.BaseAddress = new Uri("http://localhost:1310/");client.DefaultRequestHeaders.Accept.Clear();client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//添加 HTTP POSTvar 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 PUTmyProduct.Price = 80; // Update priceresponse = await client.PutAsJsonAsync(pUrl, myProduct);//删除 HTTP DELETEresponse = await client.DeleteAsync(pUrl);}//异步获取数据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对ASP.NET Web API服务实现增删改查
- ASP.NET Web API(C#)实现简单增删改查
- ASP.NET EasyUI实现增删改查
- 使用HttpClient消费ASP.NET Web API服务
- ASP.NET MVC4(2)ASP.NET MVC4 Web应用之实现简单的增删改查
- ASP.NET MVC Web API 学习笔记---联系人增删改查
- ASP.NET MVC Web API 学习笔记---联系人增删改查
- ASP.NET Web API 学习系列(一)创建与简单的增删改查
- asp.net对XML的增删改查。
- asp.net对XML的增删改查
- asp.net对XML的增删改查
- 如何使用ASP.NET对ACCESS数据库进行增删改查操作(基本型)
- ASP.NET 使用类对数据库进行增删改查操作
- ASP.NET 使用类对数据库进行增删改查操作
- HBase 使用 Java Api 实现对数据的增删改查
- web增删改查实现
- ASP.NET实现增删改查等功能(Access版)
- [VB.NET]对xml表的增删改查实现
- Redis数据结构详解
- 1005. 继续(3n+1)猜想 (25)
- 关于研究和调研的3个故事:因为热爱
- The connection to adb is down, and a severe error has occured
- 反射
- 使用HttpClient对ASP.NET Web API服务实现增删改查
- c++函数传参的一些指导原则
- Linux指令--watch,at
- Android之的性能优化方法
- Android中图案锁的实现
- 整了一个缩放算法,可以实现N倍放大,N倍缩小。
- 获取地图坐标
- cocos code IDE 自编译模拟器不能正确的运行以及断点调试连接IDE超时的解决方法
- Lesson 30 The death of a ghost