广告
返回顶部
首页 > 资讯 > 后端开发 > ASP.NET >使用HttpClient增删改查ASP.NETWebAPI服务
  • 302
分享到

使用HttpClient增删改查ASP.NETWebAPI服务

HttpClient增删改查ASP.NETWebAPI服务 2022-11-13 18:11:40 302人浏览 安东尼
摘要

本篇体验使用HttpClient对asp.net WEB api服务实现增删改查。 创建ASP.net Web API项目 新建项目,选择"ASP.NET mvc 4 We

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

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对编程网的支持。如果你想了解更多相关内容请查看下面相关链接

--结束END--

本文标题: 使用HttpClient增删改查ASP.NETWebAPI服务

本文链接: https://www.lsjlt.com/news/169506.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 使用HttpClient增删改查ASP.NETWebAPI服务
    本篇体验使用HttpClient对ASP.NET Web API服务实现增删改查。 创建ASP.NET Web API项目 新建项目,选择"ASP.NET MVC 4 We...
    99+
    2022-11-13
    HttpClient 增删改查 ASP.NET Web API服务
  • 使用HttpClient消费ASP.NETWebAPI服务案例
    本篇体验使用HttpClient消费ASP.NET Web API服务,例子比较简单。 依次点击"文件","新建","项目"...
    99+
    2022-11-13
    HttpClient 消费ASP.NET Web API服务 ASP.NET Web API服务
  • ASP.NET MVC使用Identity增删改查用户
    源码在这里:https://github.com/darrenji/UseIdentityCRUDUserInMVC,本地下载 在VS2013中创建一个MVC项目,用默认的"...
    99+
    2022-11-13
    ASP.NET MVC Identity 增删改查用户
  • Entity Framework使用DBContext实现增删改查
    有一段时间没有更新博客了,赶上今天外面下雨,而且没人约球,打算把最近对Entity Framework DBContext使用的心得梳理一下,早些时候在网上简单查过,对于最新版本的E...
    99+
    2022-11-13
    Entity Framework DBContext 增删改查
  • 如何使用Jorm增删查改数据库
    这篇文章主要介绍“如何使用Jorm增删查改数据库”,在日常操作中,相信很多人在如何使用Jorm增删查改数据库问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何使用Jorm增删...
    99+
    2022-10-18
  • PyMySQL实现增删查改的简单使用
    我们在使用MySQL的时候,可以在MySQL的客户终端来操作数据库中的表,同时,也可以使用navicat等可视化的工具来操作数据表。但是,这只是操作个别数据,如果我们想要插入10万条...
    99+
    2022-11-12
  • JavaWeb 使用DBUtils实现增删改查方式
    目录JavaWeb 使用DBUtils实现增删改查1、创建C3p0Utils类2、创建DBUtilsDao类3、创建测试类4、执行测试类Java DBUtils技术访问数据库DBUt...
    99+
    2022-11-12
  • JavaWeb如何使用DBUtils实现增删改查
    这篇文章主要讲解了“JavaWeb如何使用DBUtils实现增删改查”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“JavaWeb如何使用DBUtils实现增删改查”吧!JavaWeb 使用D...
    99+
    2023-06-21
  • ASP.NET MVC如何使用Identity增删改查用户
    这篇文章主要讲解了“ASP.NET MVC如何使用Identity增删改查用户”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“ASP.NET MVC如何使用Identity...
    99+
    2023-07-04
  • 使用PyMySQL怎么实现增删查改操作
    使用PyMySQL怎么实现增删查改操作?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。1、PyMySQL的使用步骤:2、案例:1 查询数据库中的表的信息: #&nb...
    99+
    2023-06-15
  • postgresql使用dblink跨库增删改查的步骤
    目录PostgreSQL使用dblink跨库增删改查一、使用步骤1、创建dblink扩展,连接与被连接的两个数据库都要执行下面sql2、跨库查询或增删改3、如果不想每一次都写完整的dblink连接信息,可以先起别名4、补...
    99+
    2023-04-01
    postgresql跨库增删改查 postgresql dblink跨库 postgresql跨库
  • 增删改查 elasticsearch中的文档API 的使用
    文档为何物?一个对象 就相当于mysql的一个record记录【文档】什么是文档?程序中大多的实体或对象能够被序列化为包含键值对的JSON对象,键(key)是字段(field)或属性(property)的名...
    99+
    2022-10-18
  • 使用jpa原生sql@Query操作增删改查
    jpa原生sql@Query操作增删改查 1、jpa 原生update的sql语句: 1.命名参数(推荐使用此方式):可以定义好参数名,赋值时使用@Param("参数 名"...
    99+
    2022-11-12
  • ASP.NET Core使用EF SQLite对数据库增删改查
    目录1新建ASP.NETCoreMVC应用1.1新建MVC应用1.2引入NuGet包引入教程依赖项2新建模型和上下文2.1新建模型类2.2新建上下文步骤1步骤2步骤33配置服务1直接...
    99+
    2022-11-12
  • php怎么使用mongodb进行增删查改操作
    随着大数据时代的到来,对于数据的存储和管理已经成为一个重要的问题。很多传统的关系型数据库在处理大数据时遇到了瓶颈,而NoSQL数据库则成为了一个备受关注的方向。MongoDB作为一款流行的NoSQL数据库,已经被广泛应用于各种大型Web应用...
    99+
    2023-05-14
    mongodb php
  • php如何使用mongodb进行增删查改操作
    本文小编为大家详细介绍“php如何使用mongodb进行增删查改操作”,内容详细,步骤清晰,细节处理妥当,希望这篇“php如何使用mongodb进行增删查改操作”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。一、M...
    99+
    2023-07-05
  • JavaScript节点的增删改查方法怎么使用
    本篇内容主要讲解“JavaScript节点的增删改查方法怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“JavaScript节点的增删改查方法怎么使用”吧!节点的增删改查节点的创建docu...
    99+
    2023-07-05
  • ADO.NET防SQL注入与使用参数增删改查
    一、sql注入风险及解决方案 SQL注入是指在事先定义好的SQL语句中注入额外的SQL语句,从此来欺骗数据库服务器的行为。 示例:制作会员登录功能。 登录按钮代码如下: priva...
    99+
    2022-11-13
  • .NET使用Hisql实现菜单管理(增删改查)
    一、引言 上一篇.NET集成ORM框架HiSql 已经完成了Hisql的引入,本节就把 项目中的菜单管理改成hisql的方式实现。菜单管理界面如图: 二、修改增删改查相关代码 1、...
    99+
    2022-11-13
  • 使用mybatis怎么对数据库进行增删改查
    这篇文章将为大家详细讲解有关使用mybatis怎么对数据库进行增删改查,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。select一个select 元素非常简单。例如:<!--...
    99+
    2023-05-31
    mybatis
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作