一、新建项目

二、

代码:

  Models.Products实体类  

  1. public class Product
  2. {
  3. /// <summary>
  4. /// 产品编号
  5. /// </summary>
  6. public int Pid { get; set; }
  7. /// <summary>
  8. /// 产品名称
  9. /// </summary>
  10. public string Name { get; set; }
  11. /// <summary>
  12. /// 产品价格
  13. /// </summary>
  14. public decimal Price { get; set; }
  15. /// <summary>
  16. /// 产品库存
  17. /// </summary>
  18. public int Stock { get; set; }
  19. }

  ProductsController类  

  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 WebApiDemo.Infrastructure;
  8. using WebApiDemo.Models;
  9.  
  10. namespace WebApiDemo.Controllers
  11. {
  12. public class ProductsController : ApiController
  13. {
  14. //推荐使用锁机制,能有效规避多线程时创建多个实例问题。
  15. private ProductRespository respo = ProductRespository.CurrentLock;
  16.  
  17. public IEnumerable<Product> Get()
  18. {
  19. return respo.GetAll();
  20. }
  21.  
  22. public Product Get(int pid)
  23. {
  24. return respo.GetOneById(pid);
  25. }
  26.  
  27. public Product Post(Product product)
  28. {
  29. if (ModelState.IsValid)
  30. {
  31. product = respo.AddOne(product);
  32. }
  33. return product;
  34. }
  35.  
  36. public bool Put(Product product)
  37. {
  38. if (ModelState.IsValid)
  39. {
  40. return respo.Update(product);
  41. }
  42. return false;
  43. }
  44.  
  45. public bool Delete(int pid)
  46. {
  47. return respo.Remove(pid);
  48. }
  49.  
  50. }
  51. }

  Infrastructure.ProductRespository类  

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using WebApiDemo.Models;
  6.  
  7. namespace WebApiDemo.Infrastructure
  8. {
  9. public sealed class ProductRespository
  10. {
  11.  
  12. //单例模式,先创建型(饿汉)
  13. private static ProductRespository _currentHungry = new ProductRespository();
  14. public static ProductRespository CurrentHungry
  15. {
  16. get { return _currentHungry; }
  17. }
  18.  
  19. //单例模式,按需创建型(懒汉)
  20. //单例模式,先创建型(饿汉)
  21. private static ProductRespository _currentLazy = null;
  22. public static ProductRespository CurrentLazy
  23. {
  24. get
  25. {
  26. return _currentLazy ?? (_currentLazy = new ProductRespository());
  27. }
  28. }
  29.  
  30. //单例模式,锁机制
  31. private static object lockobj = new object();
  32. private static ProductRespository _currentLock = null;
  33. public static ProductRespository CurrentLock
  34. {
  35. get
  36. {
  37. if (_currentLock == null)
  38. {
  39. lock (lockobj)
  40. {
  41. if (_currentLock == null)
  42. {
  43. _currentLock = new ProductRespository();
  44. }
  45. }
  46. }
  47. return _currentLock;
  48. }
  49. }
  50.  
  51. private List<Product> products = new List<Product>() {
  52. new Product{ Pid=,Name="Product1",Price=20.23M,Stock=},
  53. new Product{ Pid=,Name="Product2",Price=10.23M,Stock=},
  54. new Product{ Pid=,Name="Product3",Price=,Stock=},
  55. new Product{ Pid=,Name="Product4",Price=,Stock=},
  56. };
  57.  
  58. /// <summary>
  59. /// 获得所有产品
  60. /// </summary>
  61. /// <returns></returns>
  62. public IEnumerable<Product> GetAll()
  63. {
  64. return products;
  65. }
  66.  
  67. /// <summary>
  68. /// 根据ID选择产品
  69. /// </summary>
  70. /// <param name="pid">产品ID</param>
  71. /// <returns></returns>
  72. public Product GetOneById(int pid)
  73. {
  74. var selected = products.Where(p => p.Pid == pid).FirstOrDefault();
  75. return selected;
  76. }
  77.  
  78. /// <summary>
  79. /// 加入对象操作
  80. /// </summary>
  81. /// <param name="newitem"></param>
  82. /// <returns></returns>
  83. public Product AddOne(Product newitem)
  84. {
  85. newitem.Pid = products.Count + ;
  86. products.Add(newitem);
  87. return newitem;
  88. }
  89.  
  90. /// <summary>
  91. /// 根据ID删除对象
  92. /// </summary>
  93. /// <param name="pid">待删除的对象的编号</param>
  94. /// <returns></returns>
  95. public bool Remove(int pid)
  96. {
  97. var item = GetOneById(pid);
  98. if (item != null)
  99. {
  100. products.Remove(item);
  101. return true;
  102. }
  103. return false;
  104. }
  105.  
  106. /// <summary>
  107. /// 更新产品操作
  108. /// </summary>
  109. /// <param name="item"></param>
  110. /// <returns></returns>
  111. public bool Update(Product item)
  112. {
  113. var olditem = GetOneById(item.Pid);
  114. if (olditem != null)
  115. {
  116. products.Remove(olditem);
  117. products.Add(item);
  118. return true;
  119. }
  120. else
  121. {
  122. return false;
  123. }
  124. }
  125.  
  126. }
  127. }

  测试页面内容

  

  1. @{
  2. Layout = null;
  3. }
  4.  
  5. <!DOCTYPE html>
  6.  
  7. <html>
  8. <head>
  9. <meta name="viewport" content="width=device-width" />
  10. <title>Demo</title>
  11. <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
  12. <link href="~/Content/Site.css" rel="stylesheet" />
  13. <script src="~/Scripts/jquery-1.10.2.min.js"></script>
  14. <script type="text/javascript">
  15. $(function () {
  16. $("#getAllJson").click(function () {
  17. AjaxHelper("get", "", "", function (data) {
  18. $("#result").html(JSON.stringify(data));
  19. })
  20. });
  21. $("#getAllXml").click(function () {
  22. AjaxHelper("get", "", "XML", function (data) {
  23. var oSerializer = new XMLSerializer();
  24. var sXML = oSerializer.serializeToString(data);
  25. $("#result").html(sXML);
  26. })
  27. });
  28. $("#getOneJson").click(function () {
  29. AjaxHelper("get", { "pid": 1 }, "Json", function (data) {
  30. $("#result").html(JSON.stringify(data));
  31. })
  32. });
  33. $("#postOneXml").click(function () {
  34. AjaxHelper("post", { "Name": "Product5", "Price": 19.98, "Stock": 1 }, "Json", function (data) {
  35. $("#result").html(JSON.stringify(data));
  36. })
  37. });
  38. $("#putOneXml").click(function () {
  39. AjaxHelper("Put", { "Pid": 5, "Name": "Product5+", "Price": 19.98, "Stock": 1 }, "Json", function (data) {
  40. $("#result").html(JSON.stringify(data));
  41. })
  42. });
  43. $("#delOneXml").click(function () {
  44. AjaxHelper("DELETE", "", "Json", function (data) {
  45. $("#result").html(JSON.stringify(data));
  46. })
  47. });
  48.  
  49. });
  50.  
  51. function AjaxHelper(_method, _data, _datatype, _success)
  52. {
  53. $.ajax({
  54. url: "/Api/Products/5",
  55. type: _method||"get",
  56. data: _data,
  57. dataType: _datatype||"Json",
  58. success: _success
  59. });
  60. }
  61. </script>
  62. </head>
  63. <body>
  64. <div class="container">
  65. <div class="row">
  66. </div>
  67. <div class="row">
  68. <div class="btn-group">
  69. <button id="getAllJson" class="btn btn-default">获得所有(Json)</button>
  70. <button id="getAllXml" class="btn btn-default">获得所有(XML)</button>
  71. <button id="getOneJson" class="btn btn-default">获得(id=1)</button>
  72. <button id="postOneXml" class="btn btn-default">新建(post)</button>
  73. <button id="putOneXml" class="btn btn-default">更新()</button>
  74. <button id="delOneXml" class="btn btn-default">删除()</button>
  75. </div>
  76. </div>
  77. <div class="row">
  78. <div id="result">
  79.  
  80. </div>
  81. </div>
  82. </div>
  83. </body>
  84. </html>

  运行结果:

  

至此一个完整的WebAPIDemo创建完成。

  

WebAPI示例的更多相关文章

  1. ASP.NET MVC4 WebAPI若干要点

    本文仅仅是将一些可以运行无误的WebAPI示例的要点,记录下来,供自己查阅,也供刚刚学习WebAPI的读者参考之. 1.默认的API是不会过滤到action这个级别的,如果要过滤到这个级别,必须在路由 ...

  2. mvc中的webapi

    MVC中 webapi的使用 和 在其他网站中如何来调用(MVC) 1.webapi的路由规则注册在App_Start\WebApiConfig.cs文件中 2.webapi控制器继承父类 apiCo ...

  3. [开源]快速构建一个WebApi项目

    项目代码:MasterChief.DotNet.ProjectTemplate.WebApi 示例代码:https://github.com/YanZhiwei/MasterChief.Project ...

  4. Asp.Net WebApi学习教程之增删改查

    webapi简介 在asp.net中,创建一个HTTP服务,有很多方案,以前用ashx,一般处理程序(HttpHandler),现在可以用webapi 微软的web api是在vs2012上的mvc4 ...

  5. Asp.Net Core WebAPI入门整理(一)

    一.Asp.Net Core  WebAPI 1.目前版本是v1.1 2.默认路由处理和Asp.Net WebAPI有些 区别了,现在使用的是控制器路由[Route("api/Menu&qu ...

  6. 我的“第一次”,就这样没了:DDD(领域驱动设计)理论结合实践

    写在前面 插一句:本人超爱落网-<平凡的世界>这一期,分享给大家. 阅读目录: 关于DDD 前期分析 框架搭建 代码实现 开源-发布 后记 第一次听你,清风吹送,田野短笛:第一次看你,半弯 ...

  7. RESTful API URI 设计的一些总结

    非常赞的四篇文章: Resource Naming Best Practices for Designing a Pragmatic RESTful API 撰写合格的 REST API JSON 风 ...

  8. DDD(领域驱动设计)理论结合实践

    DDD(领域驱动设计)理论结合实践   写在前面 插一句:本人超爱落网-<平凡的世界>这一期,分享给大家. 阅读目录: 关于DDD 前期分析 框架搭建 代码实现 开源-发布 后记 第一次听 ...

  9. .NET Core微服务之基于Steeltoe集成Zuul实现统一API网关

    Tip: 此篇已加入.NET Core微服务基础系列文章索引,本篇接上一篇<基于Steeltoe使用Eureka实现服务注册与发现>,所演示的示例也是基于上一篇的基础上而扩展的. => ...

随机推荐

  1. 百度地图sdk使用

    1.android开发百度地图定位,我怎么老是定到几内亚湾 权限问题,首先安卓6.0之后的Android的系统需要动态申请权限. 然后百度地图的sdk的不同功能,申请的权限不同,每个功能都需要看官方文 ...

  2. PostgreSQL 存储过程/函数

    1.有用的链接 postgresql 常用小函数 Postgresql数据库的一些字符串操作函数 PostgreSQL function里面调用function PostgreSQL学习手册(函数和操 ...

  3. Python 错误总结

    1.以一种访问权限不允许的方式做了一个访问套接字的尝试. 解决方法:这个问题缘由是有端口被占用

  4. 协议 + socket import 和 form xx import *的区别 028

    一 . 网络通信协议(了解) 1 . osi 七层协议 (最好记住 面试会问) 应表会传网数物(应用层 表示层 会话层 传输层 网络层 数据链路层 物理层) 2 .tcp/ip五层 或 tcp/ip四 ...

  5. Redis未授权访问攻击过程与防范

    一.Redis未授权访问攻击过程 攻击主机:kali 目标主机:centos6.8(10.104.11.178) Redis版本:2.8 攻击条件:默认配置,未进行认证 攻击步骤详解: 1.Kali攻 ...

  6. ZoomEye(钟馗之眼)搜索技巧记录:

    做个记录方便查看 钟馗之眼: 指定搜索的组件:    app:组件名称    ver:组件版本    例:搜索 apache组件版本2.4:app:apache var:2.4指定搜素的端口:     ...

  7. pgadmin-linux-centos7.3-连接pgsql

    每次远程连接linux-centos上面的pgsql的时候,需要修改ip,命令如下: -->cd /var/lib/pgsql/data -->vi pg_hba.conf 添加ip如下, ...

  8. SQL Server Reporting Service(SSRS) 第五篇 自定义数据处理扩展DPE(Data Processing Extension)

    最近在做SSRS项目时,遇到这么一个情形:该项目有多个数据库,每个数据库都在不同的服务器,但每个数据库所拥有的数据库对象(table/view/SPs/functions)都是一模一样的,后来结合网络 ...

  9. ubuntu 16.04 安装genymotion

     以ubuntu 16.04 64bit 系统为例: 1. 下载      通过https://www.genymotion.com/download/  下载自己操作系统版本的可执行文件(     ...

  10. Beam的抽象模型

    不多说,直接上干货! Apache Beam抽象模型 计算机最简单的抽象模型是输入+计算+输出.对于数据处理类的应用来说,将计算的部分展开,变成了  数据输入  +  数据集  +  数据处理  + ...