c# 【MVC】WebApi開發執行個體__c#

來源:互聯網
上載者:User
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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.