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 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 products = new List();
        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 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 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 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" %>




    
    测试Web Api - Jquery调用
    


    
测试Web Api 添加(post) 更新(put) 删除(delete) 列表(Get) 实体(Get)
IDNameCategoryPrice

转载于:https://www.cnblogs.com/smartsmile/p/6234106.html

你可能感兴趣的:(c# 【MVC】WebApi开发实例)