ASP.NET Web API(C#)实现简单增删改查
来源:互联网 发布:手机可以做淘宝网店吗 编辑:程序博客网 时间:2024/05/01 01:18
最近学习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); } //增 public 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 () { 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. 最终效果如下:
0 0
- ASP.NET Web API(C#)实现简单增删改查
- ASP.NET MVC4(2)ASP.NET MVC4 Web应用之实现简单的增删改查
- ASP.NET Web API 学习系列(一)创建与简单的增删改查
- 使用HttpClient对ASP.NET Web API服务实现增删改查
- ASP.NET EasyUI实现增删改查
- ASP.NET MVC Web API 学习笔记---联系人增删改查
- ASP.NET MVC Web API 学习笔记---联系人增删改查
- asp.net简单新闻发布系统的增删改查
- ASP.NET 连接数据库 增删改查简单实例
- ASP.NET 连接数据库 增删改查简单实例
- web增删改查实现
- ASP.NET实现增删改查等功能(Access版)
- hbase 增删改查 api 简单操作
- ASP.NET ---- 连接Access . 增删改查
- ASP.NET ---- 连接Access . 增删改查 .
- ASP.NET基本的增删改查
- Asp.net MVC增删改查
- asp.net 4.0 gridview 增删改查
- Struts 2 的输入校验
- DBA_Oracle冷备份案例脚本本法(案例)
- Spring 的 AOP
- 使用Greendao进行批量添加数据(Android Studio读取assets下的数据库文件)
- Django数据表更改
- ASP.NET Web API(C#)实现简单增删改查
- 【WEB开发原理】servlet原理
- windows建立ftp站点-有重点
- 软考网络规划设计师考试要求
- eclipse resin4 配置preparing launch delegate 100%
- 点击Home健,退出程序,再点击图标,进入程序
- 排序(1)——冒泡排序及其优化
- 关于人脸识别基础知识blog
- MySQL 5.6 for Windows 解压缩版配置安装