本篇体验使用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)
        {
            return
                repository.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 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);
                }

                //异步获取数据
                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 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);
                }

                //异步获取数据
                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服务实现增删改查的更多相关文章

  1. 使用HttpClient操作ASP.NET Web API 2.1增删改查

    使用NuGet包安装Microsoft ASP.NET Web API 2.1 Client Libraries, 调用方式代码如下: HttpClient client = new HttpClie ...

  2. 前端使用AngularJS的$resource,后端ASP.NET Web API,实现增删改查

    AngularJS中的$resource服务相比$http服务更适合与RESTful服务进行交互.本篇后端使用ASP.NET Web API, 前端使用$resource,实现增删改查. 本系列包括: ...

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

    本篇体验使用HttpClient消费ASP.NET Web API服务,例子比较简单. 依次点击"文件","新建","项目". 选择&quo ...

  4. ASP.NET从零开始学习EF的增删改查

           ASP.NET从零开始学习EF的增删改查           最近辞职了,但是离真正的离职还有一段时间,趁着这段空档期,总想着写些东西,想来想去,也不是很明确到底想写个啥,但是闲着也是够 ...

  5. 基于gin的golang web开发:mysql增删改查

    Go语言访问mysql数据库需要用到标准库database/sql和mysql的驱动.标准库的Api使用比较繁琐这里再引入另一个库github.com/jmoiron/sqlx. go get git ...

  6. Android(java)学习笔记193:利用谷歌API对数据库增删改查(推荐使用)

    接下来我们通过项目案例来介绍:这个利用谷歌API对数据库增删改查 1.首先项目图: 2.这里的布局文件activity_main.xml: <LinearLayout xmlns:android ...

  7. 通过flask实现web页面简单的增删改查bootstrap美化版

    通过flask实现web页面简单的增删改查bootstrap美化版 项目目录结构 [root@node1 python]# tree -L 2 . ├── animate.css ├── fileut ...

  8. 通过flask实现web页面简单的增删改查

    通过flask实现web页面简单的增删改查 # 1.后台程序falsk_web01.py #coding:utf-8 from flask import Flask,render_template,r ...

  9. Android(java)学习笔记136:利用谷歌API对数据库增删改查(推荐使用)

    接下来我们通过项目案例来介绍:这个利用谷歌API对数据库增删改查 1. 首先项目图: 2. 这里的布局文件activity_main.xml: <LinearLayout xmlns:andro ...

随机推荐

  1. Android 6.0 变更

    Android 6.0(API 级别 23)除了提供诸多新特性和功能外,还对系统和 API 行为做出了各种变更.本文重点介绍您应该了解并在开发应用时加以考虑的一些主要变更. 如果您之前发布过 Andr ...

  2. [转] caffe数据层参数说明

    原文地址:http://www.cnblogs.com/denny402/p/5070928.html 稍有修改: 数据层是每个模型的最底层,是模型的入口,不仅提供数据的输入,也提供数据从Blobs转 ...

  3. laravel 批量更新

    /** * 转发动态和资讯数量统计 */ public function forwardCounts(FeedModel $feedModel) { //统计动态转发的id $feeds=$feedM ...

  4. 2018-2019-2 网络对抗技术 20165301 Exp4 恶意代码分析

    2018-2019-2 网络对抗技术 20165301 Exp4 恶意代码分析 实验内容 系统运行监控 使用如计划任务,每隔一分钟记录自己的电脑有哪些程序在联网,连接的外部IP是哪里.运行一段时间并分 ...

  5. leetcode 题集

    775. Global and Local Inversions 统计相邻元素组成的逆序对(local inversion)和全局逆序对的数量(global inversion) 思路:local i ...

  6. 【LOJ】#2569. 「APIO2016」最大差分

    题解 第一个子任务直接询问最大最小,每次可以问出来两个,再最大最小-1再问两个,最多问\(\frac{N + 1}{2}\)次就还原出了序列 第二个子任务由于差分肯定会大于等于\(\lceil \fr ...

  7. Codeforces Round #533 (Div. 2) E - Helping Hiasat 最大团

    E - Helping Hiasat 裸的最大团,写了一种 2 ^ (m / 2)  * (m / 2)的复杂度的壮压, 应该还有更好的方法. #include<bits/stdc++.h> ...

  8. POJ 3009 Curling 2.0(DFS + 模拟)

    题目链接:http://poj.org/problem?id=3009 题意: 题目很复杂,直接抽象化解释了.给你一个w * h的矩形格子,其中有包含一个数字“2”和一个数字“3”,剩下的格子由“0” ...

  9. Lighthouse前端性能优化测试工具

    在前端开发中,对于自己开发的app或者web page性能的好坏,一直是让前端开发很在意的话题.我们需要专业的网站测试工具,让我们知道自己的网页还有哪些需要更为优化的方面,我自己尝试了一款工具:Lig ...

  10. 浅谈2-SAT(待续)

    2-SAT问题,其实是一个逻辑互斥问题.做了两道裸题之后仔细想来,和小时候做过的“有两个女生,如果A是女生,那么B一定不是女生.A和C性别相同,求A.B.C三人的性别.”几乎是一样的. 对于这道题我们 ...