ASP.NET Web API(C#)实现简单增删改查
2016-09-09 14:12
429 查看
最近学习web Api,自己动手做出了一个小例子
1. 在vs2015中新建 ASP.NET WEB Application 项目2.在“新ASP.NET MVC 4项目”对话框中,选择“Web API”并点击“OK”
3. 在Models文件夹,添加一个模型
命名为Product.cs
编辑Product.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HelloWebApi2.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } } }
4. 添加仓储类
在Models文件夹中,添加一个名为IProductRepository的仓储接口类,并编辑:
在Models文件夹中,添加ProductRepository.cs类,用以实现此接口:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HelloWebApi2.Models { public class ProductRepository : IProductRepository { private List<Product> products = new List<Product>(); private int _nextId = 1; //初始化数据 public ProductRepository() { Add(new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }); Add(new Product { Id = 2, Name = "Yp-yo", Category = "Yoys", Price = 3.75M }); Add(new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }); } //根据id查询数据 public Product Get(int id) { return products.Find(p => p.Id == id); } //增 publi 4000 c Product Add(Product item) { if (item == null) { throw new ArgumentNullException("item"); } item.Id = _nextId++; products.Add(item); return item; } //查询全部数据 public IEnumerable<Product> GetAll() { return products; } public void Remove(int id) { products.RemoveAll(p => p.Id == id); } //更新数据 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; } } }
5. 添加控制器
在Controllers文件夹中,添加一个名为ProductsController的控制器:
注意:此控制器继承于ApiController
using HelloWebApi2.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; using System.Web.Mvc; namespace HelloWebApi2.Controllers { public class ProductsController : ApiController { // GET: Products static readonly IProductRepository repository = new ProductRepository(); public IEnumerable<Product> GetAllProducts() { return repository.GetAll(); } public Product GetProduct(int id) { Product item = repository.Get(id); if (item == null) { //throw new HttpResponseException(HttpStatusCode.NotFound); throw new Exception("查询的id不存在!"); } 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<Product>(HttpStatusCode.Created, item); string uri = Url.Link("DefaultApi", new { id = item.Id }); response.Headers.Location = new Uri(uri); return response; } //Update public void PutProduct(int id,Product product) { product.Id = id; if (!repository.Update(product)) { //throw new HttpResponseException(HttpStatusCode.NotFound); throw new Exception("更新的数据出错!"); } } //Delete public void DeleteProduct(int id) { Product item = repository.Get(id); if (item == null) { //throw new HttpResponseException(HttpStatusCode.NotFound); throw new Exception("删除的数据出错!"); } repository.Remove(id); } } }
6. 接下来,开始建立视图,便于测试
每一个方法前都有一句注释,标识了该方法的针对的请求的类型(取决于方法的开头),以及要请求到该方法,需要使用的url。
这些url是有规律的,见下图:
为了方便,这里直接使用/Views/Home/Index.cshtml,删除所有初始内容,修改为下面内容:
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width" /> <title></title> </head> <body> <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script> $(document).ready(function () { var load = function () { $("#products").empty(); $.getJSON("/api/products/", function (data) { $.each(data, function (key, val) { var str = val.Name + ':$' + val.Price; var ele = $("<li id=" + val.Id + ">" + "<strong>" + val.Id + "</strong>" +". "+ str + "</li>") ele.appendTo($('#products')); }); }); }; load(); //用于保存用户输入数据 var Product = { create: function () { Id: ""; Name: ""; Category: ""; Price: ""; return Product; } } //添加一条记录 请求类型:POST 请求url: /api/Products //请求到ProductsController.cs中的 public HttpResponseMessage PostProduct(Product item) 方法 $("#addItem").click(function () { var newProduct = Product.create(); newProduct.Name = $("#name").val(); newProduct.Category = $("#category").val(); newProduct.Price = $("#price").val(); $.ajax({ url: "/api/Products", type: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify(newProduct), success: function () { alert("添加成功!"); load(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("请求失败,消息:" + textStatus + " " + errorThrown); } }); }); //先根据Id查询记录 请求类型:GET 请求url: /api/Products/Id //请求到ProductsController.cs中的 public Product GetProduct(int id) 方法 $("#showItem").click(function () { var inputId = $("#id2").val(); $("#name2").val(""); $("#category2").val(""); $("#price2").val(""); $.ajax({ url: "/api/Products/" + inputId, type: "GET", contentType: "application/json; charset=urf-8", success: function (data) { $("#name2").val(data.Name); $("#category2").val(data.Category); $("#price2").val(data.Price); load(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("请求失败,消息:" + textStatus + " " + errorThrown); } }); }); //修改该Id的记录 请求类型:PUT 请求url: /api/Products/Id //请求到ProductsController.cs中的 public void PutProduct(int id, Product product) 方法 $("#editItem").click(function () { var inputId = $("#id2").val(); console.log(inputId) var newProduct = Product.create(); newProduct.Name = $("#name2").val(); newProduct.Category = $("#category2").val(); newProduct.Price = $("#price2").val(); $.ajax({ url: "/api/Products/" + inputId, type: "PUT", data: JSON.stringify(newProduct), contentType: "application/json; charset=urf-8", success: function () { alert("修改成功! "); load(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("请求失败,消息:" + textStatus + " " + errorThrown); } }); }); //删除输入Id的记录 请求类型:DELETE 请求url: /api/Products/Id //请求到ProductsController.cs中的 public void DeleteProduct(int id) 方法 $("#removeItem").click(function () { d1a4 var inputId = $("#id2").val(); $.ajax({ url: "/api/Products/" + inputId, type: "DELETE", contentType: "application/json; charset=uft-8", success: function (data) { alert("Id为 " + inputId + " 的记录删除成功!"); load(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("请求失败,消息:" + textStatus + " " + errorThrown); } }); }); }); </script> <div id="body"> <div> <h1>All Products</h1> <ul id="products"></ul> </div> <section> <h2>添加记录</h2> Name:<input id="name" type="text" /><br /> Category:<input id="category" type="text" /> Price:<input id="price" type="text" /><br /> <input id="addItem" type="button" value="添加" /> </section> <section> <br /> <br /> <h2>修改记录</h2> Id:<input id="id2" type="text" /><br /> Name:<input id="name2" type="text" /><br /> Category:<input id="category2" type="text" /> Price:<input id="price2" type="text" /><br /> <input id="showItem" type="button" value="查询" /> <input id="editItem" type="button" value="修改" /> <input id="removeItem" type="button" value="删除" /> </section> </div> </body> </html>
6. 最终效果如下:
相关文章推荐
- 前端使用AngularJS的$resource,后端ASP.NET Web API,实现增删改查
- ASP.net C# 非常简单的实现分页
- sql server 关于表中只增标识问题 C# 实现自动化打开和关闭可执行文件(或 关闭停止与系统交互的可执行文件) ajaxfileupload插件上传图片功能,用MVC和aspx做后台各写了一个案例 将小写阿拉伯数字转换成大写的汉字, C# WinForm 中英文实现, 国际化实现的简单方法 ASP.NET Core 2 学习笔记(六)ASP.NET Core 2 学习笔记(三)
- c#Asp.Net简单实现发送电子邮件的功用
- ASP.NET Web API 学习系列(一)创建与简单的增删改查
- ADO.NET .net core2.0添加json文件并转化成类注入控制器使用 简单了解 iTextSharp实现HTML to PDF ASP.NET MVC 中 Autofac依赖注入DI 控制反转IOC 了解一下 C# AutoMapper 了解一下
- 简单C#、asp.net mvc验证码的实现
- 一个简单的AJAX实现,基于C#的ASP.Net,包括服务器端的程序代码
- 使用HttpClient对ASP.NET Web API服务实现增删改查
- ASP.NET MVC4 WEB API入门 第二篇:ASP.NET MVC入门基础(2)—— 简单登录功能的实现
- ASP.NET Web API 实现客户端Basic(基本)认证 之简单实现
- 一个简单的AJAX实现,基于C#的ASP.Net,包括服务器端的程序代码
- ASP.net C# 非常简单的实现分页
- ASP.NET Web API 实现客户端Basic(基本)认证 之简单实现
- asp.net Web API 身份验证 不记名令牌验证 Bearer Token Authentication 简单实现
- 【C#】对异步请求处理程序IHttpAsyncHandler的理解和分享一个易用性封装 【手记】走近科学之为什么明明实现了IEnumerable<T>的类型却不能调用LINQ扩展方法 【手记】手机网页弹出层后屏蔽底层的滑动响应 【手记】ASP.NET提示“未能创建类型”处理 【Web】一个非常简单的移动web消息框 【手记】解决EXCEL跑SQL遇“查询无法运行或数据库表无法打开...”
- asp.net,C#,html控件的File控件实现多文件上传简单实例,vs2010
- 开始一个简单的ASP.NET Web API 2 (C#)
- 前端使用AngularJS的$resource,后端ASP.NET Web API,实现增删改查
- C#实现多级子目录Zip压缩解压实例 NET4.6下的UTC时间转换 [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 asp.Net Core免费开源分布式异常日志收集框架Exceptionless安装配置以及简单使用图文教程 asp.net core异步进行新增操作并且需要判断某些字段是否重复的三种解决方案 .NET Core开发日志