WebAPI示例
一、新建项目


二、

代码:
Models.Products实体类
public class Product
{
/// <summary>
/// 产品编号
/// </summary>
public int Pid { get; set; }
/// <summary>
/// 产品名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 产品价格
/// </summary>
public decimal Price { get; set; }
/// <summary>
/// 产品库存
/// </summary>
public int Stock { get; set; }
}
ProductsController类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiDemo.Infrastructure;
using WebApiDemo.Models; namespace WebApiDemo.Controllers
{
public class ProductsController : ApiController
{
//推荐使用锁机制,能有效规避多线程时创建多个实例问题。
private ProductRespository respo = ProductRespository.CurrentLock; public IEnumerable<Product> Get()
{
return respo.GetAll();
} public Product Get(int pid)
{
return respo.GetOneById(pid);
} public Product Post(Product product)
{
if (ModelState.IsValid)
{
product = respo.AddOne(product);
}
return product;
} public bool Put(Product product)
{
if (ModelState.IsValid)
{
return respo.Update(product);
}
return false;
} public bool Delete(int pid)
{
return respo.Remove(pid);
} }
}
Infrastructure.ProductRespository类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebApiDemo.Models; namespace WebApiDemo.Infrastructure
{
public sealed class ProductRespository
{ //单例模式,先创建型(饿汉)
private static ProductRespository _currentHungry = new ProductRespository();
public static ProductRespository CurrentHungry
{
get { return _currentHungry; }
} //单例模式,按需创建型(懒汉)
//单例模式,先创建型(饿汉)
private static ProductRespository _currentLazy = null;
public static ProductRespository CurrentLazy
{
get
{
return _currentLazy ?? (_currentLazy = new ProductRespository());
}
} //单例模式,锁机制
private static object lockobj = new object();
private static ProductRespository _currentLock = null;
public static ProductRespository CurrentLock
{
get
{
if (_currentLock == null)
{
lock (lockobj)
{
if (_currentLock == null)
{
_currentLock = new ProductRespository();
}
}
}
return _currentLock;
}
} private List<Product> products = new List<Product>() {
new Product{ Pid=,Name="Product1",Price=20.23M,Stock=},
new Product{ Pid=,Name="Product2",Price=10.23M,Stock=},
new Product{ Pid=,Name="Product3",Price=,Stock=},
new Product{ Pid=,Name="Product4",Price=,Stock=},
}; /// <summary>
/// 获得所有产品
/// </summary>
/// <returns></returns>
public IEnumerable<Product> GetAll()
{
return products;
} /// <summary>
/// 根据ID选择产品
/// </summary>
/// <param name="pid">产品ID</param>
/// <returns></returns>
public Product GetOneById(int pid)
{
var selected = products.Where(p => p.Pid == pid).FirstOrDefault();
return selected;
} /// <summary>
/// 加入对象操作
/// </summary>
/// <param name="newitem"></param>
/// <returns></returns>
public Product AddOne(Product newitem)
{
newitem.Pid = products.Count + ;
products.Add(newitem);
return newitem;
} /// <summary>
/// 根据ID删除对象
/// </summary>
/// <param name="pid">待删除的对象的编号</param>
/// <returns></returns>
public bool Remove(int pid)
{
var item = GetOneById(pid);
if (item != null)
{
products.Remove(item);
return true;
}
return false;
} /// <summary>
/// 更新产品操作
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Update(Product item)
{
var olditem = GetOneById(item.Pid);
if (olditem != null)
{
products.Remove(olditem);
products.Add(item);
return true;
}
else
{
return false;
}
} }
}
测试页面内容
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Demo</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/Site.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#getAllJson").click(function () {
AjaxHelper("get", "", "", function (data) {
$("#result").html(JSON.stringify(data));
})
});
$("#getAllXml").click(function () {
AjaxHelper("get", "", "XML", function (data) {
var oSerializer = new XMLSerializer();
var sXML = oSerializer.serializeToString(data);
$("#result").html(sXML);
})
});
$("#getOneJson").click(function () {
AjaxHelper("get", { "pid": 1 }, "Json", function (data) {
$("#result").html(JSON.stringify(data));
})
});
$("#postOneXml").click(function () {
AjaxHelper("post", { "Name": "Product5", "Price": 19.98, "Stock": 1 }, "Json", function (data) {
$("#result").html(JSON.stringify(data));
})
});
$("#putOneXml").click(function () {
AjaxHelper("Put", { "Pid": 5, "Name": "Product5+", "Price": 19.98, "Stock": 1 }, "Json", function (data) {
$("#result").html(JSON.stringify(data));
})
});
$("#delOneXml").click(function () {
AjaxHelper("DELETE", "", "Json", function (data) {
$("#result").html(JSON.stringify(data));
})
});
});
function AjaxHelper(_method, _data, _datatype, _success)
{
$.ajax({
url: "/Api/Products/5",
type: _method||"get",
data: _data,
dataType: _datatype||"Json",
success: _success
});
}
</script>
</head>
<body>
<div class="container">
<div class="row">
</div>
<div class="row">
<div class="btn-group">
<button id="getAllJson" class="btn btn-default">获得所有(Json)</button>
<button id="getAllXml" class="btn btn-default">获得所有(XML)</button>
<button id="getOneJson" class="btn btn-default">获得(id=1)</button>
<button id="postOneXml" class="btn btn-default">新建(post)</button>
<button id="putOneXml" class="btn btn-default">更新()</button>
<button id="delOneXml" class="btn btn-default">删除()</button>
</div>
</div>
<div class="row">
<div id="result">
</div>
</div>
</div>
</body>
</html>
运行结果:

至此一个完整的WebAPIDemo创建完成。
WebAPI示例的更多相关文章
- ASP.NET MVC4 WebAPI若干要点
本文仅仅是将一些可以运行无误的WebAPI示例的要点,记录下来,供自己查阅,也供刚刚学习WebAPI的读者参考之. 1.默认的API是不会过滤到action这个级别的,如果要过滤到这个级别,必须在路由 ...
- mvc中的webapi
MVC中 webapi的使用 和 在其他网站中如何来调用(MVC) 1.webapi的路由规则注册在App_Start\WebApiConfig.cs文件中 2.webapi控制器继承父类 apiCo ...
- [开源]快速构建一个WebApi项目
项目代码:MasterChief.DotNet.ProjectTemplate.WebApi 示例代码:https://github.com/YanZhiwei/MasterChief.Project ...
- Asp.Net WebApi学习教程之增删改查
webapi简介 在asp.net中,创建一个HTTP服务,有很多方案,以前用ashx,一般处理程序(HttpHandler),现在可以用webapi 微软的web api是在vs2012上的mvc4 ...
- Asp.Net Core WebAPI入门整理(一)
一.Asp.Net Core WebAPI 1.目前版本是v1.1 2.默认路由处理和Asp.Net WebAPI有些 区别了,现在使用的是控制器路由[Route("api/Menu&qu ...
- 我的“第一次”,就这样没了:DDD(领域驱动设计)理论结合实践
写在前面 插一句:本人超爱落网-<平凡的世界>这一期,分享给大家. 阅读目录: 关于DDD 前期分析 框架搭建 代码实现 开源-发布 后记 第一次听你,清风吹送,田野短笛:第一次看你,半弯 ...
- RESTful API URI 设计的一些总结
非常赞的四篇文章: Resource Naming Best Practices for Designing a Pragmatic RESTful API 撰写合格的 REST API JSON 风 ...
- DDD(领域驱动设计)理论结合实践
DDD(领域驱动设计)理论结合实践 写在前面 插一句:本人超爱落网-<平凡的世界>这一期,分享给大家. 阅读目录: 关于DDD 前期分析 框架搭建 代码实现 开源-发布 后记 第一次听 ...
- .NET Core微服务之基于Steeltoe集成Zuul实现统一API网关
Tip: 此篇已加入.NET Core微服务基础系列文章索引,本篇接上一篇<基于Steeltoe使用Eureka实现服务注册与发现>,所演示的示例也是基于上一篇的基础上而扩展的. => ...
随机推荐
- [USACO08OCT]牧场散步Pasture Walking BZOJ1602 LCA
题目描述 The N cows (2 <= N <= 1,000) conveniently numbered 1..N are grazing among the N pastures ...
- javascript的offset、client、scroll、screen使用方法
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAHuCAYAAABpm/53AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjw
- Log4web独立config配置
第一步:config配置,独立文件的 <?xml version="1.0" encoding="utf-8"?> <configuratio ...
- shell 获取hive表结构
hive -S -e "select * from db_name.table_name limit 0"|grep table_name|xargs -n1|sed 's/tab ...
- jvm问题定位:cpu持续25%
某次代码提交后审核,观察应用CPU占用持续25%, 感觉应该是某个线程写的有问题, 在linux服务器上查看cpu却是正常 windows平台线程查看工具: Process Explorer, ...
- esper(2)-事件类型
1.pojo package com.ebc.eventtype.pojo.pojo1; import cn.hutool.core.collection.CollUtil; import com.e ...
- Autel MaxiSys Pro MS908P
Autel MaxiSys pro MS908P is an evolutionary smart solution for specialized automotive diagnosis and ...
- hdu 6287
选出来比较合适的博客 https://blog.csdn.net/Tony5t4rk/article/details/80490711 https://blog.csdn.net/Game_Acm/a ...
- 用navigator.geolocation.getCurrentPosition在IOS10以上的系统无法定位
昨天老板告诉我代码有Bug(定位失败),于是各种测试最终发现IOS10以上版本手机不能成功(穷,买不起iphone,测试不完全),先贴失败代码: var city =""; nav ...
- 不要在Application中缓存数据
在你的App中的很多地方都需要使用到数据信息,它可能是一个session token,一次费时计算的结果等等,通常为了避免Activity之间传递数据的开销,会将这些数据通过持久化来存储. 有人建 ...