c# 【MVC】WebApi开发实例

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; }
    }
}

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);
    }
}

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;
        }
    }
}
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);
        }
    }
}
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html>
<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>测试Web Api - Jquery调用</title>
    <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
</head>
<body>
    <div>
    <fieldset>
        <legend>测试Web Api
        </legend>
        <a href="javascript:add()">添加(post)</a>
        <a href="javascript:update(1)">更新(put)</a>
        <a href="javascript:deletes(1)">删除(delete)</a>
        <a href="javascript:getall()">列表(Get)</a>
        <a href="javascript:getone()">实体(Get)</a>
    </fieldset>
    <table id="products">
    <thead>
        <tr><th>ID</th><th>Name</th><th>Category</th><th>Price</th></tr>
    </thead>
    <tbody id="looptr">
    </tbody>
    </table>
    <script type="text/javascript">
        $(function () {
            getall();
        });

        //获取列表
        function getall() {
            var str = "";
            $.getJSON("/api/products", function (products) {
                alert(JSON.stringify(products));
                $.each(products, function (index, product) {
                    str += "<tr>"
                    str += "<td>" + products[index].Id + "</td>";
                    str += "<td>" + products[index].Name + "</td>";
                    str += "<td>" + products[index].Category + "</td>";
                    str += "<td>" + products[index].Price + "</td>";
                    str += "<tr>"
                });
                $("#looptr").html(str);
            });
        }

        //获取某条信息
        function getone() {
            var str = "";
            $.getJSON("/api/products/1", function (product) {
                alert(JSON.stringify(product));
                str += "<tr>"
                str += "<td>" + product.Id + "</td>";
                str += "<td>" + product.Name + "</td>";
                str += "<td>" + product.Category + "</td>";
                str += "<td>" + product.Price + "</td>";
                str += "<tr>"
                $("#looptr").html(str);
            });
        }

        //新增
        function add() {
            $.ajax({
                url: "/api/products/",
                type: "POST",
                data: { "Id": 4, "Name": "test", "Category": "Parry", "Price": 239 },
                success: function (data) { alert(JSON.stringify(data)); }
            });
        }

        //更新
        function update(id) {
            $.ajax({
                url: "/api/products?id=4",
                type: "Put",
                data: { "Id": 1, "Name": "moditest", "Category": "Parry", "Price": 89 },
                success: function (data) { alert(JSON.stringify(data)); }
            });
        }

        //删除
        function deletes(id) {
            $.ajax({
                url: "/api/products/4",
                type: "DELETE",
                success: function (data) { alert(data); }
            });
        }
    </script>       
    </div>
</body>
</html>

原文地址:https://www.cnblogs.com/smartsmile/p/6234106.html