1.新建webapi项目

2.配置WebApiConfig

public const string DEFAULT_ROUTE_NAME = "MyDefaultRoute";
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: DEFAULT_ROUTE_NAME,
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
); // 取消注释下面的代码行可对具有 IQueryable 或 IQueryable<T> 返回类型的操作启用查询支持。
// 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。
// 有关详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=279712。
//config.EnableQuerySupport(); // 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行
// 有关详细信息,请参阅: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
}

3.在models文件新建person模型

public class Person
{
public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }

4.在models文件中添加IPersonRepository

interface IPersonRepository
{
IEnumerable<Person> GetAll(); Person Get(int id); Person Add(Person person); void Remove(int id); bool Update(Person person); }

5.在models文件中添加仓库实现

public class PersonRepository : IPersonRepository
{ // We are using the list and _fakeDatabaseID to represent what would // most likely be a database of some sort, with an auto-incrementing ID field: private List<Person> _people = new List<Person>(); private int _fakeDatabaseID = 1; public PersonRepository()
{ // For the moment, we will load some sample data during initialization. this.Add(new Person { LastName = "Lennon", FirstName = "John" }); this.Add(new Person { LastName = "McCartney", FirstName = "Paul" }); this.Add(new Person { LastName = "Harrison", FirstName = "George" }); this.Add(new Person { LastName = "Starr", FirstName = "Ringo" }); } public IEnumerable<Person> GetAll()
{ return _people; } public Person Get(int id)
{ return _people.Find(p => p.Id == id); } public Person Add(Person person)
{ if (person == null)
{ throw new ArgumentNullException("person"); } person.Id = _fakeDatabaseID++; _people.Add(person); return person; } public void Remove(int id)
{ _people.RemoveAll(p => p.Id == id); } public bool Update(Person person)
{ if (person == null)
{ throw new ArgumentNullException("person"); } int index = _people.FindIndex(p => p.Id == person.Id); if (index == -1)
{ return false; } _people.RemoveAt(index); _people.Add(person); return true; } }

6.在controllers中添加apiController为PersonController

public class PersonController : ApiController
{
static readonly IPersonRepository databasePlaceholder = new PersonRepository(); public IEnumerable<Person> GetAllPeople()
{ return databasePlaceholder.GetAll(); } public Person GetPersonByID(int id)
{ Person person = databasePlaceholder.Get(id); if (person == null)
{ throw new HttpResponseException(HttpStatusCode.NotFound); } return person; } public HttpResponseMessage PostPerson(Person person)
{ person = databasePlaceholder.Add(person); string apiName = WebApi.WebApiConfig.DEFAULT_ROUTE_NAME; var response = this.Request.CreateResponse<Person>(HttpStatusCode.Created, person); string uri = Url.Link(apiName, new { id = person.Id }); response.Headers.Location = new Uri(uri); return response; } public bool PutPerson(Person person)
{ if (!databasePlaceholder.Update(person))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return true; } public void DeletePerson(int id)
{ Person person = databasePlaceholder.Get(id); if (person == null)
{ throw new HttpResponseException(HttpStatusCode.NotFound); } databasePlaceholder.Remove(id); } }

以上就完成了webapi的简单搭建。接下来创建客户端来访问webapi。

7.新建console项目,添加webapi Core Library。

添加引用

using System.Net.Http;

using Newtonsoft.Json.Linq;

private const string url = "http://localhost:43571/";
static void Main(string[] args)
{
Console.WriteLine("Retreive All The People:"); JArray people = GetAllPerson(); foreach (var person in people)
{ Console.WriteLine(person); } // WRITE A SPECIFIC PERSON TO CONSOLE (JSON): Console.WriteLine(Environment.NewLine + "Retreive a Person by ID:"); JObject singlePerson = GetPerson(2); Console.WriteLine(singlePerson); // ADD NEW PERSON, THEN WRITE TO CONSOLE (JSON): Console.WriteLine(Environment.NewLine + "Add a new Person and return the new object:"); JObject newPerson = AddPerson("Atten", "John"); Console.WriteLine(newPerson); // UPDATE AN EXISTING PERSON, THEN WRITE TO CONSOLE (JSON): Console.WriteLine(Environment.NewLine + "Update an existing Person and return a boolean:"); // Pretend we already had a person's data: JObject personToUpdate = GetPerson(2); string newLastName = "Richards"; Console.WriteLine("Update Last Name of " + personToUpdate + "to " + newLastName); // Pretend we don't already know the Id: int id = personToUpdate.Value<int>("Id"); string FirstName = personToUpdate.Value<string>("FirstName"); string LastName = personToUpdate.Value<string>("LastName"); if (UpdatePerson(id, newLastName, FirstName))
{ Console.WriteLine(Environment.NewLine + "Updated person:"); Console.WriteLine(GetPerson(id)); } // DELETE AN EXISTING PERSON BY ID: Console.WriteLine(Environment.NewLine + "Delete person object:"); DeletePerson(5); // WRITE THE UPDATED LIST TO THE CONSOLE: { // WRITE ALL PEOPLE TO CONSOLE Console.WriteLine("Retreive All The People using classes:"); people = GetAllPerson(); foreach (var person in people)
{ Console.WriteLine(person); } } Console.Read(); } /// <summary>
/// get all Person
/// </summary>
/// <returns></returns>
static JArray GetAllPerson()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync(url + "api/person").Result;
return response.Content.ReadAsAsync<JArray>().Result;
} static JObject GetPerson(int id)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync(url + "api/person/" + id).Result;
return response.Content.ReadAsAsync<JObject>().Result;
} static JObject AddPerson(string newLastName, string newFirstName)
{
var newPerson = new { LastName = newLastName, FirstName = newFirstName }; HttpClient client = new HttpClient(); client.BaseAddress = new Uri(url); var response = client.PostAsJsonAsync("api/person", newPerson).Result; return response.Content.ReadAsAsync<JObject>().Result; } // Sends HTTP PUT to Person Controller on API with Anonymous Object: static bool UpdatePerson(int personId, string newLastName, string newFirstName)
{ // Initialize an anonymous object representing a the modified Person record: var newPerson = new { id = personId, LastName = newLastName, FirstName = newFirstName }; HttpClient client = new HttpClient(); client.BaseAddress = new Uri(url); var response = client.PutAsJsonAsync("api/person/", newPerson).Result; return response.Content.ReadAsAsync<bool>().Result; } // Sends HTTP DELETE to Person Controller on API with Id Parameter: static void DeletePerson(int id)
{ HttpClient client = new HttpClient(); client.BaseAddress = new Uri(url); var relativeUri = "api/person/" + id.ToString(); var response = client.DeleteAsync(relativeUri).Result; client.Dispose(); }

参考地址:http://typecastexception.com/post/2013/07/01/Creating-a-Clean-Minimal-Footprint-ASPNET-WebAPI-Project-with-VS-2012-and-ASPNET-MVC-4.aspx

http://typecastexception.com/post/2013/07/03/Building-Out-a-Clean-REST-ful-WebApi-Service-with-a-Minimal-WebApi-Project.aspx

源码下载:webApiDemo

WebApi增删改查Demo的更多相关文章

  1. 【讲义提纲】以一个实战新闻cms增删改查demo为例,给学院国创队伍培训php

    PHP实战基础——以一个新闻cms的增删改查为例 一.        环境配置 二.        数据库创建 三.        增删改查demo 连接数据库 <?php $link=mysq ...

  2. mvc模式jsp+servel+dbutils oracle基本增删改查demo

    mvc模式jsp+servel+dbutils oracle基本增删改查demo 下载地址

  3. mvc模式jsp+servel+jdbc oracle基本增删改查demo

    mvc模式jsp+servel+jdbc oracle基本增删改查demo 下载地址

  4. SSH登录与增删改查demo详解+源代码

    点击下载,测试绝对可用SSH整合框架登录加增删改查demo 下载地址:http://download.csdn.net/detail/qq_33599520/9784679   一.框架概述 spri ...

  5. ssm学习(四)--完整的增删改查demo

    上一篇文章简要介绍了将sping mvc加入整个框架,算是完成了ssm的集成.本节继续前面的内容,结合spring mvc做一个简单的增删改查demo. 1.首先,重写一下GeckoList.jsp页 ...

  6. ztree--插件实现增删改查demo(完整版)

    ztree--插件实现增删改查demo(完整版) var setting = {                 async: {                     enable: true,  ...

  7. AJAX 调用WebService 、WebApi 增删改查(笔记)

    经过大半天努力,终于完成增删改查了!心情有点小激动!!对于初学者的我来说,一路上都是迷茫,坑!!虽说网上有资料,可动手起来却不易(初学者的我).(苦逼啊!) WebService 页面: /// &l ...

  8. hibernate之增删改查demo

    package dao; import java.util.ArrayList; import java.util.List; import org.hibernate.Query; import o ...

  9. asp.net数据库增删改查demo

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

随机推荐

  1. 在Linux下安装RabbitMQ

    Installing on RPM-based Linux (CentOS, Fedora, OpenSuse, RedHat) 安装新版本的RabbitMQ出错: centos端口转发神器:soca ...

  2. HTML CSS边框阴影的实现

    一款用CSS控制背景图像平铺,从而实现区域边框阴影的效果,虽然用到了图片,但可贵之处是本代码不管你需要阴影的区域是多大,它都能自动适应,因些还是很值得收藏一下的,兼容所有的IE浏览器. <!DO ...

  3. 搭建自己的 github.io 博客

    1.前言 github.io 是基于 Github 的 repo 管理,这意味着咱们对其是有绝对的控制,这个跟放在第三方的平台比,可控性要好太多. 使用 github pages 服务搭建博客的好处有 ...

  4. xtrabackup-增量备份

    增量备份之所以能工作是因为每个innodb的page都包含日志序列号(LSN).LSN是整个数据库的版本号. 增量备份会拷贝那些LSN比备份开始时新的页.有两种算法用来计算查找这些页:第一种,支持所有 ...

  5. SharePoint 2013 Step by Step—— 为终端用户提供故障恢复的解决方案 Part I

    Disaster Recovery,我把他直译"故障恢复",或者也可以翻译成 "灾难复原 ".光字面意思就可以领会到,当SharePoint Server发生了 ...

  6. Groovy 学习手册(1)

    1. 需要安装的软件 Java / Groovy 对应 Java 和 Groovy,你需要安装以下软件: Java JDK,例如 JDK 8 IDE,例如 Eclipse,NetBeans 8 Gro ...

  7. stm8 io口重映射

    STM8S003F3端口可以设置重映射,如pin16的PC6管脚,默认复用功能是SPI_MOSI功能,可以重映射为TIM1_CH1,也就是timer1的1通道.映射方式并不像STM32那样有个AFR寄 ...

  8. Android 如何添加一个apk使模拟器和真机都编译进去 m

    添加一个apk都需要将LOCAL_PACKAGE_NAME的值添加到PRODUCT_PACKAGES才行.而PRODUCT_PACKAGES一般在build/target/product/目录下的文件 ...

  9. php分享二十二:php面向对象

    1:static访问符 在类中使用static有两种主要用途.定义静态成员和定义静态方法.静态成员只保留一个变量的值,这个值对所有实例都是有效的 类的方法是static的,他所访问的属性也必须是sta ...

  10. 好的 IOS 学习网站

    http://www.objc.io/contributors.html codeproject. http://www.codeproject.com/KB/iPhone/