ASP.NET WebApi 增删改查
本篇是接着上一篇《ASP.NET WebApi 入门》来介绍的。
习惯说 CRUD操作,它的意思是"创建、 读取、 更新和删除"四个基本的数据库操作。许多 HTTP 服务通过REST的 Api 进行CRUD 操作。在本教程中,生成非常简单的 web API 来管理产品的列表。每个产品将包含名称、 价格和类别,再加上一个产品 id。访问Uri对应如下:
| 行动 | HTTP 方法 | 相对 URI |
|---|---|---|
| 获取所有产品的列表 | GET | /api/Product |
| 根据ID得到一个产品 | GET | /api/Product/id |
| 根据Category获取产品的列表 | GET | /api/Product?Category=类别 |
| 创建一个新的产品 | POST | /api/Product |
| 根据ID更新一个产品 | PUT | /api/Product/id |
| 根据ID删除一个产品 | DELETE | /api/Product/id |
在Models文件夹下,创建IProductRepository.cs:
using System.Collections.Generic; namespace ApiDemo01.Models
{
/// <summary>仓储操作接口</summary>
public interface IProductRepository
{
IEnumerable<Product> GetAll();
Product Get(int id);
Product Add(Product item);
void Remove(int id);
bool Update(Product item);
}
}
在Models文件夹下,创建ProductRepository.cs:
using System;
using System.Collections.Generic; namespace ApiDemo01.Models
{
/// <summary>仓储操作实现</summary>
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;
}
}
}
注:存储库中保持在本地内存中的列表。在实际的应用中,您将存储的数据在外部,任一数据库或在云存储中。存储库模式将使易于更改以后实施。
由于是接着上一篇博文介绍的项目,所以这里修改Controllers文件下的ProductController.cs:
using ApiDemo01.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http; namespace ApiDemo01.Controllers
{
public class ProductController : ApiController
{
//TODO:接口引用具体实例(后面介绍MEF,使得接口解除使用具体实现)
static readonly IProductRepository repository = new ProductRepository(); //获取所有产品
public IEnumerable<Product> GetAllProducts()
{
return repository.GetAll();
} //根据ID获取一个产品
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));
} //添加一个产品
//默认情况下,Web API 框架将响应状态代码设置为 200 (OK)。
//但根据 HTTP/1.1 协议中,当 POST 请求的结果在创造一种资源,服务器应该回复状态为 201 (已创建)。 //服务器将创建一个资源,它应在响应的位置标题中包括的新的资源的 URI。 //public Product PostProduct(Product item)
//{
// item = repository.Add(item);
// return item;
//} //对上面方法进行改进
//返回类型现在是HttpResponseMessage。
//通过返回HttpResponseMessage而不是产品,我们可以控制的 HTTP 响应消息,包括状态代码和位置标头的详细信息。
public HttpResponseMessage PostProduct(Product item)
{
item = repository.Add(item);
//创建的HttpResponseMessage ,并自动将产品对象的序列化表示形式写入到身体火炭的响应消息。
var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item); string uri = Url.Link("DefaultApi", new { id = item.ID });
response.Headers.Location = new Uri(uri);
return response;
} //根据ID更新一个产品
public void PutProduct(int id, Product product)
{
product.ID = id;
if (!repository.Update(product))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
} //根据ID删除一个产品
public void DeleteProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
} repository.Remove(id);
}
} #region 此段代码是上一篇博文里介绍的方式,这里注释掉
//public class ProductController : ApiController
//{
// //模拟数据
// List<Product> pList = new List<Product>
// {
// new Product{ID=1, Name="Dell", Category="电脑" , Price=3500 },
// new Product{ID=2, Name="Apple", Category="手机" , Price=5500 },
// new Product{ID=3, Name="HP", Category="电脑" , Price=3000 }
// }; // //获取产品集合
// public IEnumerable<Product> GetProducts()
// {
// return pList;
// } // //根据产品ID获取一个产品
// public IHttpActionResult GetProduct(int id)
// {
// var product = pList.FirstOrDefault((p) => p.ID == id);
// if (product == null)
// {
// return NotFound();
// }
// return Ok(product);
// }
//}
#endregion
}
注:以上采用封装数据库仓储操作方式!
通过前面的介绍,似乎WebApi应用并不难。其实,很多高级使用(如:OData)还没涉及到讲解。有人说,WebApi和WebService很像,似乎有点为了“淘汰”WCF技术而生。但没有WCF强大,只是更容易使用。
好了。这节内容并没有演示如何界面展示!我也是正在学习这项技术当中,本着先过一边官方的例子后,再弄一个完整的DEMO!
ASP.NET WebApi 增删改查的更多相关文章
- AJAX 调用WebService 、WebApi 增删改查(笔记)
经过大半天努力,终于完成增删改查了!心情有点小激动!!对于初学者的我来说,一路上都是迷茫,坑!!虽说网上有资料,可动手起来却不易(初学者的我).(苦逼啊!) WebService 页面: /// &l ...
- ASP.NET MVC增删改查
ASP.NET MVC中的增删改查 基本都要使用C控制器中的两个action来完成操作,一个用于从主界面跳转到新页面.同时将所需操作的数据传到新界面,另一个则对应新界面的按钮,用于完成操作.将数据传回 ...
- asp.net数据库增删改查demo
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- WebApi增删改查Demo
1.新建webapi项目 2.配置WebApiConfig public const string DEFAULT_ROUTE_NAME = "MyDefaultRoute"; p ...
- AJAX 调用WebService 、WebApi 增删改查
WebService 页面: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 3 ...
- asp.net Mvc 增删改查
1.创建项目 已经创建好项目了 2.创建数据库 使用这个数据库或者自己创建一个数据库,一个表就好,简单 USE [LearnAdminlte] GO /****** Object: Table [db ...
- ASP.NET Identity系列02,在ASP.NET MVC中增删改查用户
本篇体验在ASP.NET MVC中使用ASP.NET Identity增删改查用户. 源码在这里:https://github.com/darrenji/UseIdentityCRUDUserInMV ...
- Asp.net WebApi 项目示例(增删改查)
1.WebApi是什么 ASP.NET Web API 是一种框架,用于轻松构建可以由多种客户端(包括浏览器和移动设备)访问的 HTTP 服务.ASP.NET Web API 是一种用于在 .NET ...
- Asp.Net WebApi学习教程之增删改查
webapi简介 在asp.net中,创建一个HTTP服务,有很多方案,以前用ashx,一般处理程序(HttpHandler),现在可以用webapi 微软的web api是在vs2012上的mvc4 ...
随机推荐
- 《UNIX级别编程环境》注意读出信号(2)
1.功能sigaction sigaction动与指定信号相关联的处理动作.其函数原型例如以下: #inlcude <signal.h> int sigaction(int signo,c ...
- js中的open和showModalDialog
一.window.open()支持环境: JavaScript1.0+/JScript1.0+/Nav2+/IE3+/Opera3+ 二.基本语法:window.open(pageURL,name,p ...
- malloc,free简单的实现
有关标准库首先简要malloc其原理: 标准库内部通过一个双向链表.管理在堆中动态分配的内存. malloc函数分配内存时会附加若干(一般是12个)字节,存放控制信息. 该信息 ...
- C++ Primer 学习笔记_56_ 类和数据抽象 --消息处理演示示例
拷贝控制 --消息处理演示样例 说明: 有些类为了做一些工作须要对复制进行控制. 为了给出这种样例,我们将概略定义两个类,这两个类可用于邮件处理应用程序.Message类和 Folder类分别表示电子 ...
- Nagios显示器MySQL一个错误:NRPE: Unable to read output具体的解决过程
前言:nagios介面.见监测mysql服务错误,如下面: Warning:NRPE: Unable to read output 1,跟nagios显示器server上check下 1.1.运行ch ...
- IMSDroid遇到注册问题(蘼1S 计3等一下 Android4.4)
最近的研究视频通话,开源项目IMSDroid编译测试,这实在是不幸的,饭1 Android4.1和大米3 Android4.4该系统不是对生命和死亡登记.... .后来通过大神日志分析和建议.发现改变 ...
- 了解你的家公家IP
我们总是在不在家的时候,须要訪问我们的电脑或设备,因为大多数人拥有来自ISP的动态IP,我们能够做一个小型设备来给我们的Android手机发送一个简单的通知,这样我们就能够总有IP用了,有 ...
- 【地图API】为何您的坐标不准?如何纠偏?
原文:[地图API]为何您的坐标不准?如何纠偏? 摘要:各种坐标体系之间如何转换?到底有哪些坐标体系?什么是火星坐标?为什么我的坐标,在地图上显示会有偏移?本文详细解答以上问题.最后给出坐标拾取工具. ...
- 浅谈 js 正则之 test 方法
原文:浅谈 js 正则之 test 方法 其实我很少用这个,所以之前一直没注意这个问题,自从落叶那厮写了个变态的测试我才去看了下这东西.先来看个东西吧. var re = /\d/; console. ...
- Flex在使用无线电的button切换直方图横坐标和叙述性说明
1.问题叙述性说明 一组单选button,有周和月之分,选择"周",柱状图横坐标显示的是周,纵坐标显示的是人数:选择"月",柱状图横坐标显示的月,纵坐标显示的是 ...