c# 【MVC】WebApi开发实例

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace ProductStore.Models  
  8. {  
  9.     //商品实体类  
  10.     public class Product  
  11.     {  
  12.         public int Id { getset; }  
  13.         public string Name { getset; }  
  14.         public string Category { getset; }  
  15.         public decimal Price { getset; }  
  16.     }  
  17. }  
  1. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ProductStore.Models { //商品实体类 public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } } }

[csharp] view plain copy
print ?
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace ProductStore.Models  
  8. {  
  9.     //商品接口  
  10.     interface IProductRepository  
  11.     {  
  12.         IEnumerable<Product> GetAll();  
  13.         Product Get(int id);  
  14.         Product Add(Product item);  
  15.         void Remove(int id);  
  16.         bool Update(Product item);  
  17.     }  
  18. }  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProductStore.Models
{
    //商品接口
    interface IProductRepository
    {
        IEnumerable<Product> GetAll();
        Product Get(int id);
        Product Add(Product item);
        void Remove(int id);
        bool Update(Product item);
    }
}

[csharp] view plain copy
print ?
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace ProductStore.Models  
  7. {  
  8.     //商品操作类  
  9.     public class ProductRepository : IProductRepository  
  10.     {  
  11.         private List<Product> products = new List<Product>();  
  12.         private int _nextId = 1;  
  13.   
  14.         public ProductRepository()  
  15.         {  
  16.             Add(new Product { Name = "Tomato soup", Category = "Groceries", Price = 1.39M });  
  17.             Add(new Product { Name = "Yo-yo", Category = "Toys", Price = 3.75M });  
  18.             Add(new Product { Name = "Hammer", Category = "Hardware", Price = 16.99M });  
  19.         }  
  20.   
  21.         public IEnumerable<Product> GetAll()  
  22.         {  
  23.             return products;  
  24.         }  
  25.   
  26.         public Product Get(int id)  
  27.         {  
  28.             return products.Find(p => p.Id == id);  
  29.         }  
  30.   
  31.         public Product Add(Product item)  
  32.         {  
  33.             if (item == null)  
  34.             {  
  35.                 throw new ArgumentNullException("item");  
  36.             }  
  37.   
  38.             item.Id = _nextId++;  
  39.             products.Add(item);  
  40.             return item;  
  41.         }  
  42.   
  43.         public void Remove(int id)  
  44.         {  
  45.             products.RemoveAll(p => p.Id == id);  
  46.         }  
  47.   
  48.         public bool Update(Product item)  
  49.         {  
  50.             if (item == null)  
  51.             {  
  52.                 throw new ArgumentNullException("item");  
  53.             }  
  54.             int index = products.FindIndex(p => p.Id == item.Id);  
  55.             if (index == -1)  
  56.             {  
  57.                 return false;  
  58.             }  
  59.             products.RemoveAt(index);  
  60.             products.Add(item);  
  61.             return true;  
  62.         }  
  63.     }  
  64. }  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProductStore.Models
{
    //商品操作类
    public class ProductRepository : IProductRepository
    {
        private List<Product> products = new List<Product>();
        private int _nextId = 1;

        public ProductRepository()
        {
            Add(new Product { Name = "Tomato soup", Category = "Groceries", Price = 1.39M });
            Add(new Product { Name = "Yo-yo", Category = "Toys", Price = 3.75M });
            Add(new Product { Name = "Hammer", Category = "Hardware", Price = 16.99M });
        }

        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 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;
        }
    }
}
[csharp] view plain copy
print ?
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using ProductStore.Models;  
  8. using System.Text;  
  9.   
  10. //控制器  
  11. namespace ProductStore.Controllers  
  12. {  
  13.     public class ProductsController : ApiController  
  14.     {  
  15.         /* 
  16.          * 微软的web api是在vs2012上的mvc4项目绑定发行的,它提出的web api是完全基于RESTful标准的, 
  17.          * 完全不同于之前的(同是SOAP协议的)wcf和webService,它是简单,代码可读性强的,上手快的, 
  18.          * 如果要拿它和web服务相比,我会说,它的接口更标准,更清晰,没有混乱的方法名称, 
  19.          *  
  20.          * 有的只有几种标准的请求,如get,post,put,delete等,它们分别对应的几个操作,下面讲一下: 
  21.          * GET:生到数据列表(默认),或者得到一条实体数据 
  22.          * POST:添加服务端添加一条记录,记录实体为Form对象 
  23.          * PUT:添加或修改服务端的一条记录,记录实体的Form对象,记录主键以GET方式进行传输 
  24.          * DELETE:删除 服务端的一条记录          
  25.          */  
  26.         static readonly IProductRepository repository = new ProductRepository();  
  27.   
  28.         public IEnumerable<Product> GetAllProducts()  
  29.         {  
  30.             return repository.GetAll();  
  31.         }  
  32.   
  33.         public Product GetProduct(int id)  
  34.         {  
  35.             Product item = repository.Get(id);  
  36.             if (item == null)  
  37.             {  
  38.                 throw new HttpResponseException(HttpStatusCode.NotFound);  
  39.             }  
  40.             return item;  
  41.         }  
  42.   
  43.         public IEnumerable<Product> GetProductsByCategory(string category)  
  44.         {  
  45.             return repository.GetAll().Where(  
  46.                 p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));  
  47.         }  
  48.   
  49.         public HttpResponseMessage PostProduct(Product item)  
  50.         {  
  51.             item = repository.Add(item);  
  52.             return new HttpResponseMessage(HttpStatusCode.OK)  
  53.             {  
  54.                 Content = new StringContent("add success", System.Text.Encoding.UTF8, "text/plain")  
  55.             };  
  56.         }  
  57.   
  58.         public void PutProduct(int id, Product product)  
  59.         {  
  60.             product.Id = id;  
  61.             if (!repository.Update(product))  
  62.             {  
  63.                 throw new HttpResponseException(HttpStatusCode.NotFound);  
  64.             }  
  65.         }  
  66.   
  67.         public void DeleteProduct(int id)  
  68.         {  
  69.             repository.Remove(id);  
  70.         }  
  71.     }  
  72. }  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ProductStore.Models;
using System.Text;

//控制器
namespace ProductStore.Controllers
{
    public class ProductsController : ApiController
    {
        /*
         * 微软的web api是在vs2012上的mvc4项目绑定发行的,它提出的web api是完全基于RESTful标准的,
         * 完全不同于之前的(同是SOAP协议的)wcf和webService,它是简单,代码可读性强的,上手快的,
         * 如果要拿它和web服务相比,我会说,它的接口更标准,更清晰,没有混乱的方法名称,
         * 
         * 有的只有几种标准的请求,如get,post,put,delete等,它们分别对应的几个操作,下面讲一下:
         * GET:生到数据列表(默认),或者得到一条实体数据
         * POST:添加服务端添加一条记录,记录实体为Form对象
         * PUT:添加或修改服务端的一条记录,记录实体的Form对象,记录主键以GET方式进行传输
         * DELETE:删除 服务端的一条记录         
         */
        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);
            }
            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);
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("add success", System.Text.Encoding.UTF8, "text/plain")
            };
        }

        public void PutProduct(int id, Product product)
        {
            product.Id = id;
            if (!repository.Update(product))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

        public void DeleteProduct(int id)
        {
            repository.Remove(id);
        }
    }
}
  1. <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>  
  2.   
  3. <!DOCTYPE html>  
  4. <html>  
  5. <head runat="server">  
  6.     <meta name="viewport" content="width=device-width" />  
  7.     <title>测试Web Api - Jquery调用</title>  
  8.     <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>  
  9. </head>  
  10. <body>  
  11.     <div>  
  12.     <fieldset>  
  13.         <legend>测试Web Api  
  14.         </legend>  
  15.         <a href="javascript:add()">添加(post)</a>  
  16.         <a href="javascript:update(1)">更新(put)</a>  
  17.         <a href="javascript:deletes(1)">删除(delete)</a>  
  18.         <a href="javascript:getall()">列表(Get)</a>  
  19.         <a href="javascript:getone()">实体(Get)</a>  
  20.     </fieldset>  
  21.     <table id="products">  
  22.     <thead>  
  23.         <tr><th>ID</th><th>Name</th><th>Category</th><th>Price</th></tr>  
  24.     </thead>  
  25.     <tbody id="looptr">  
  26.     </tbody>  
  27.     </table>  
  28.     <script type="text/javascript">  
  29.         $(function () {  
  30.             getall();  
  31.         });  
  32.   
  33.         //获取列表  
  34.         function getall() {  
  35.             var str = "";  
  36.             $.getJSON("/api/products", function (products) {  
  37.                 alert(JSON.stringify(products));  
  38.                 $.each(products, function (index, product) {  
  39.                     str += "<tr>"  
  40.                     str += "<td>" + products[index].Id + "</td>";  
  41.                     str += "<td>" + products[index].Name + "</td>";  
  42.                     str += "<td>" + products[index].Category + "</td>";  
  43.                     str += "<td>" + products[index].Price + "</td>";  
  44.                     str += "<tr>"  
  45.                 });  
  46.                 $("#looptr").html(str);  
  47.             });  
  48.         }  
  49.   
  50.         //获取某条信息  
  51.         function getone() {  
  52.             var str = "";  
  53.             $.getJSON("/api/products/1", function (product) {  
  54.                 alert(JSON.stringify(product));  
  55.                 str += "<tr>"  
  56.                 str += "<td>" + product.Id + "</td>";  
  57.                 str += "<td>" + product.Name + "</td>";  
  58.                 str += "<td>" + product.Category + "</td>";  
  59.                 str += "<td>" + product.Price + "</td>";  
  60.                 str += "<tr>"  
  61.                 $("#looptr").html(str);  
  62.             });  
  63.         }  
  64.   
  65.         //新增  
  66.         function add() {  
  67.             $.ajax({  
  68.                 url: "/api/products/",  
  69.                 type: "POST",  
  70.                 data: { "Id": 4, "Name": "test", "Category": "Parry", "Price": 239 },  
  71.                 success: function (data) { alert(JSON.stringify(data)); }  
  72.             });  
  73.         }  
  74.   
  75.         //更新  
  76.         function update(id) {  
  77.             $.ajax({  
  78.                 url: "/api/products?id=4",  
  79.                 type: "Put",  
  80.                 data: { "Id": 1, "Name": "moditest", "Category": "Parry", "Price": 89 },  
  81.                 success: function (data) { alert(JSON.stringify(data)); }  
  82.             });  
  83.         }  
  84.   
  85.         //删除  
  86.         function deletes(id) {  
  87.             $.ajax({  
  88.                 url: "/api/products/4",  
  89.                 type: "DELETE",  
  90.                 success: function (data) { alert(data); }  
  91.             });  
  92.         }  
  93.     </script>         
  94.     </div>  
  95. </body>  
  96. </html> 
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值