电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術(shù)文章
文章詳情頁

使用HttpClient增刪改查ASP.NET Web API服務(wù)

瀏覽:138日期:2022-06-08 15:57:54

本篇體驗(yàn)使用HttpClient對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){    returnrepository.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 獲取編號為1的產(chǎn)品

使用HttpClient查詢某個產(chǎn)品

在同一個解決方案下創(chuàng)建一個控制臺程序。

依次點(diǎn)擊"工具","庫程序包管理器","程序包管理器控制臺",輸入如下:

Install-Package Microsoft.AspNet.WebApi.Client

在控制臺程序下添加Product類,與ASP.NET Web API中的對應(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);}    }}

把控制臺項(xiàng)目設(shè)置為啟動項(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 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 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 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 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);    }    }    }}

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接

標(biāo)簽: ASP.NET
相關(guān)文章:
主站蜘蛛池模板: ge超声波测厚仪-电动涂膜机-电动划格仪-上海洪富 | BESWICK球阀,BESWICK接头,BURKERT膜片阀,美国SEL继电器-东莞市广联自动化科技有限公司 | 脉冲布袋除尘器_除尘布袋-泊头市净化除尘设备生产厂家 | 药品/药物稳定性试验考察箱-埃里森仪器设备(上海)有限公司 | 深圳离婚律师咨询「在线免费」华荣深圳婚姻律师事务所专办离婚纠纷案件 | 螺杆式冷水机-低温冷水机厂家-冷冻机-风冷式-水冷式冷水机-上海祝松机械有限公司 | 皮带机_移动皮带机_大倾角皮带机_皮带机厂家 - 新乡市国盛机械设备有限公司 | 彼得逊采泥器-定深式采泥器-电动土壤采样器-土壤样品风干机-常州索奥仪器制造有限公司 | 耙式干燥机_真空耙式干燥机厂家-无锡鹏茂化工装备有限公司 | 压滤机滤板_厢式_隔膜_板框压滤机滤板厂家价格型号材质-大凯环保 | 示波器高压差分探头-国产电流探头厂家-南京桑润斯电子科技有限公司 | 酒吧霸屏软件_酒吧霸屏系统,酒吧微上墙,夜场霸屏软件,酒吧点歌软件,酒吧互动游戏,酒吧大屏幕软件系统下载 | 搅拌磨|搅拌球磨机|循环磨|循环球磨机-无锡市少宏粉体科技有限公司 | 亮点云建站-网站建设制作平台| COD分析仪|氨氮分析仪|总磷分析仪|总氮分析仪-圣湖Greatlake | 披萨石_披萨盘_电器家电隔热绵加工定制_佛山市南海区西樵南方综合保温材料厂 | 清水-铝合金-建筑模板厂家-木模板价格-铝模板生产「五棵松」品牌 | 青岛代理记账_青岛李沧代理记账公司_青岛崂山代理记账一个月多少钱_青岛德辉财税事务所官网 | 企业微信scrm管理系统_客户关系管理平台_私域流量运营工具_CRM、ERP、OA软件-腾辉网络 | 成都热收缩包装机_袖口式膜包机_高速塑封机价格_全自动封切机器_大型套膜机厂家 | 液压油缸生产厂家-山东液压站-济南捷兴液压机电设备有限公司 | 正压密封性测试仪-静态发色仪-导丝头柔软性测试仪-济南恒品机电技术有限公司 | 东莞猎头公司_深圳猎头公司_广州猎头公司-广东万诚猎头提供企业中高端人才招聘服务 | 杭州货架订做_组合货架公司_货位式货架_贯通式_重型仓储_工厂货架_货架销售厂家_杭州永诚货架有限公司 | 包装盒厂家_纸盒印刷_礼品盒定制-济南恒印包装有限公司 | 咖啡加盟-咖啡店加盟-咖啡西餐厅加盟-塞纳左岸咖啡西餐厅官网 | 北京开源多邦科技发展有限公司官网 | 真石漆,山东真石漆,真石漆厂家,真石漆价格-山东新佳涂料有限公司 | 杭州厂房降温,车间降温设备,车间通风降温,厂房降温方案,杭州嘉友实业爽风品牌 | PTFE接头|聚四氟乙烯螺丝|阀门|薄膜|消解罐|聚四氟乙烯球-嘉兴市方圆氟塑制品有限公司 | 贝朗斯动力商城(BRCPOWER.COM) - 买叉车蓄电池上贝朗斯商城,价格更超值,品质有保障! | 上海单片机培训|重庆曙海培训分支机构—CortexM3+uC/OS培训班,北京linux培训,Windows驱动开发培训|上海IC版图设计,西安linux培训,北京汽车电子EMC培训,ARM培训,MTK培训,Android培训 | 学校用栓剂模,玻璃瓶轧盖钳,小型安瓿熔封机,实验室安瓿熔封机-长沙中亚制药设备有限公司 | 家用净水器代理批发加盟_净水机招商代理_全屋净水器定制品牌_【劳伦斯官网】 | 沉降天平_沉降粒度仪_液体比重仪-上海方瑞仪器有限公司 | POS机官网 - 拉卡拉POS机免费办理|官网在线申请入口 | 越南专线物流_东莞国际物流_东南亚专线物流_行通物流 | 江苏大隆凯科技有限公司 | 板材品牌-中国胶合板行业十大品牌-环保板材-上海声达板材 | 电磁辐射仪-电磁辐射检测仪-pm2.5检测仪-多功能射线检测仪-上海何亦仪器仪表有限公司 | 活性炭-蜂窝-椰壳-柱状-粉状活性炭-河南唐达净水材料有限公司 |