web api (.NET 4.5)
摘自http://blog.csdn.net/fangxing80/article/details/7318289
在刚刚发布的 ASP.NET MVC 4 中,有一个值得注意的新特性——Web Api,微软官方的介绍是:
ASP.NET MVC 4 中包含了Web API 它能够构建HTTP服务以支撑更广泛的客户端,包括浏览器,手机和平板电脑的框架。
ASP.NET Web API是非常棒的构建服务的框架,遵循REST架构风格,而且它支持的RPC模式。
从 .NET 3.5 开始 WCF 已经支持用 WebHttpBinding 构建 RESTful Web 服务,基于 WCF 框架的 Web Api 还是建立在 WCF Message 栈上,因为 REST 的工作原理有所不同,它不需要依赖 SOAP 协议,因此 WCF 消息管道对于它经过了特殊的消息优化。但 REST 集成在 WCF 消息管道上还是不理想,所以微软提出在 ASP.NET 平台上构建REST服务,也就有了现在 ASP.NET MVC 4 中的 Web Api。
引用 WCF 在 Codeplex 上的声明:
Announcement: WCF Web API is now ASP.NET Web API! ASP.NET Web API released with ASP.NET MVC 4 Beta.
The WCF Web API and WCF support for jQuery content on this site wll removed by the end of 2012.
如果对 REST WCF 框架熟悉的童鞋,可以参看下面的 WCF Web Api 到 ASP.NET Web Api 的映射表:
| WCF Web API | ASP.NET Web API |
| Service | Web API controller |
| Operation | Action |
| Service contract | Not applicable |
| Endpoint | Not applicable |
| URI templates | ASP.NET Routing |
| Message handlers | Same |
| Formatters | Same |
| Operation handlers | Filters, model binders |
下面来看看如何使用 ASP.NET Web Api (使用的是 VS11 Beta 版)
(1) 创建 ASP.NET MVC 4 工程时选择 Web Api
创建出的工程中,Controllers 目录下会有一个 ValuesController.cs 注意它继承于 ApiController
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http;
- using System.Web.Http;
- namespace MvcApplication1.Controllers
- {
- public class ValuesController : ApiController
- {
- // GET /api/values
- public IEnumerable<string> Get()
- {
- return new string[] { "value1", "value2" };
- }
- // GET /api/values/5
- public string Get(int id)
- {
- return "value";
- }
- // POST /api/values
- public void Post(string value)
- {
- }
- // PUT /api/values/5
- public void Put(int id, string value)
- {
- }
- // DELETE /api/values/5
- public void Delete(int id)
- {
- }
- }
- }
在 Global.cs 中,注册了 Api 的 Url Map: api/{controller}/{id} 每个"Action"是通过 Http谓词(GET/POST/PUT/DELETE)映射的。
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
- }
(2) 增加一个自定义 Model
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace MvcApplication1.Models
- {
- public class Task
- {
- public string Id { get; set; }
- public string Title { get; set; }
- public string Content { get; set; }
- public int Status { get; set; }
- }
- }
(3) 增加一个自定义 Repository
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using MvcApplication1.Models;
- namespace MvcApplication1.Repositories
- {
- public class TaskRepository
- {
- private List<Task> _tasks;
- public TaskRepository()
- {
- _tasks = new List<Task> {
- new Task { Id="T001", Title="title1", Content="content1" },
- new Task { Id="T002", Title="title2", Content="content2" },
- new Task { Id="T003", Title="title3", Content="content3" },
- new Task { Id="T004", Title="title4", Content="content4" },
- };
- }
- public IEnumerable<Task> GetAll()
- {
- return _tasks;
- }
- public Task FindById(string id)
- {
- return _tasks.FirstOrDefault(t => t.Id == id);
- }
- public void Add(Task task)
- {
- _tasks.Add(task);
- }
- public void RemoveById(string id)
- {
- var task = _tasks.FirstOrDefault(t => t.Id == id);
- if (task != null)
- _tasks.Remove(task);
- }
- }
- }
(4) 增加 TaskController
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http;
- using System.Web.Http;
- using MvcApplication1.Models;
- namespace MvcApplication1.Controllers
- {
- public class TasksController : ApiController
- {
- private Repositories.TaskRepository _taskRepository = new Repositories.TaskRepository();
- // GET /api/tasks
- public IQueryable<Task> Get()
- {
- return _taskRepository.GetAll().AsQueryable();
- }
- // GET /api/tasks/5
- public Task Get(string id)
- {
- return _taskRepository.FindById(id);
- }
- // POST /api/tasks
- public void Post(Task task)
- {
- _taskRepository.Add(task);
- }
- // DELETE /api/tasks/5
- public void Delete(string id)
- {
- _taskRepository.RemoveById(id);
- }
- }
- }
运行:
同样,客户端可以通过 Http Header 的 Accept 指定返回数据的格式。默认是支持:appliction/xml 和 application/json
当想返回比如 image/jpeg 这样的图片格式时,需要添加 MediaTypeFormatter
比如:当指定某个 Task 时,通过指定 Accept : image/jpeg 获取该 Task 的图片信息。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http.Formatting;
- using System.Web;
- using MvcApplication1.Models;
- namespace MvcApplication1.Repositories
- {
- public class TaskPictureFormatter : MediaTypeFormatter
- {
- protected override bool CanWriteType(Type type)
- {
- return (type == typeof(Task));
- }
- public TaskPictureFormatter()
- {
- SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg"));
- }
- protected override System.Threading.Tasks.Task OnWriteToStreamAsync(Type type, object value,
- System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders,
- FormatterContext formatterContext, System.Net.TransportContext transportContext)
- {
- var task = value as Task;
- if (task != null)
- {
- var data = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/TaskImages/" + task.Id + ".png"));
- return stream.WriteAsync(data, 0, data.Length);
- }
- else
- {
- throw new HttpException((int)System.Net.HttpStatusCode.NotFound, "task is not found", null);
- }
- }
- }
- }
注意:当找不到对应的图片时,抛出 HttpException 这样可以给客户端更加友好的错误提示。
当输入一个错误的Id:
另外一个强大的功能是 Web Api 的 SelfHost,通过 HttpSelfHostServer 就可以非常方便的将 Web Api 寄宿到 IIS 以外的应用中去了。
作为简单数据交换的应用场景十分有用。
注意工程需要添加以下引用:
- System.Net.Http
- System.Web.Extensions
- System.Web.Http
- System.Web.Http.Common
- System.Web.Http.SelfHost
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web.Http;
- using System.Web.Http.SelfHost;
- namespace WebApiSelfHostTest
- {
- class Program
- {
- static void Main(string[] args)
- {
- var config = new HttpSelfHostConfiguration("http://localhost:8080");
- config.Routes.MapHttpRoute(
- "API Default", "api/{controller}/{id}",
- new { id = RouteParameter.Optional });
- using (HttpSelfHostServer server = new HttpSelfHostServer(config))
- {
- server.OpenAsync().Wait();
- Console.WriteLine("HttpServer is opening, Press Enter to quit.");
- Console.ReadLine();
- }
- }
- }
- public class Product
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public decimal Price { get; set; }
- }
- public class ProductsController : ApiController
- {
- public IEnumerable<Product> GetAllProducts()
- {
- return new List<Product>
- {
- new Product() { Id = 1, Name = "Gizmo 1", Price = 1.99M },
- new Product() { Id = 2, Name = "Gizmo 2", Price = 2.99M },
- new Product() { Id = 3, Name = "Gizmo 3", Price = 3.99M }
- };
- }
- }
- }


web api (.NET 4.5)的更多相关文章
- 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用
由于ASP.NET Web API具有与ASP.NET MVC类似的编程方式,再加上目前市面上专门介绍ASP.NET Web API 的书籍少之又少(我们看到的相关内容往往是某本介绍ASP.NET M ...
- bootstrap + requireJS+ director+ knockout + web API = 一个时髦的单页程序
也许单页程序(Single Page Application)并不是什么时髦的玩意,像Gmail在很早之前就已经在使用这种模式.通常的说法是它通过避免页面刷新大大提高了网站的响应性,像操作桌面应用程序 ...
- Hello Web API系列教程——Web API与国际化
软件国际化是在软件设计和文档开发过程中,使得功能和代码设计能处理多种语言和文化习俗,在创建不同语言版本时,不需要重新设计源程序代码的软件工程方法.这在很多成熟的软件开发平台中非常常见.对于.net开发 ...
- ASP.NET Web API 跨域访问(CORS)
一.客户端用JSONP请求数据 如果你想用JSONP来获得跨域的数据,WebAPI本身是不支持javascript的callback的,它返回的JSON是这样的: {"YourSignatu ...
- Web Api 入门实战 (快速入门+工具使用+不依赖IIS)
平台之大势何人能挡? 带着你的Net飞奔吧!:http://www.cnblogs.com/dunitian/p/4822808.html 屁话我也就不多说了,什么简介的也省了,直接简单概括+demo ...
- Web APi之认证(Authentication)两种实现方式【二】(十三)
前言 上一节我们详细讲解了认证及其基本信息,这一节我们通过两种不同方式来实现认证,并且分析如何合理的利用这两种方式,文中涉及到的基础知识,请参看上一篇文中,就不再叙述废话. 序言 对于所谓的认证说到底 ...
- angular2系列教程(八)In-memory web api、HTTP服务、依赖注入、Observable
大家好,今天我们要讲是angular2的http功能模块,这个功能模块的代码不在angular2里面,需要我们另外引入: index.html <script src="lib/htt ...
- 我这么玩Web Api(二):数据验证,全局数据验证与单元测试
目录 一.模型状态 - ModelState 二.数据注解 - Data Annotations 三.自定义数据注解 四.全局数据验证 五.单元测试 一.模型状态 - ModelState 我理解 ...
- 我这么玩Web Api(一):帮助页面或用户手册(Microsoft and Swashbuckle Help Page)
前言 你需要为客户编写Api调用手册?你需要测试你的Api接口?你需要和前端进行接口对接?那么这篇文章应该可以帮到你.本文将介绍创建Web Api 帮助文档页面的两种方式,Microsoft Help ...
- [译] 在Web API 2 中实现带JSON的Patch请求
原文链接:The Patch Verb in Web API 2 with JSON 我想在.NET4.6 Web API 2 项目中使用Patch更新一个大对象中的某个字断,这才意识到我以前都没有用 ...
随机推荐
- android:强大的图片下载和缓存库Picasso
1.Picasso简单介绍 Picasso是Square公司出品的一个强大的图片下载和缓存图片库.官方网址是:http://square.github.io/picasso/ 仅仅须要一句代码就能够将 ...
- The Building Blocks- Components of EA Part 2- Process, People, Network and Time
1. Zachman Framework Information (Data) - Answer the Question 'What?' Contextual: List of Things imp ...
- Java获取客户端真实IP地址的两种方法
在JSP里,获取客户端的IP地址的方法是:request.getRemoteAddr(),这种方法在大部分情况下都是有效的.但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实I ...
- idea maven 无法加载已经安装的模块
新建了一下maven项目,下面新建了一个模块,某一个模块clean install之后,别的模块虽然使用dependency标签引入了,但是仍然无法使用, 这个时候,应该重新建立一个项目,将原有项目的 ...
- NPOI兼容 excel2003,2007版本
根据项目需要,需要对excel进行导入导出,所以选择NPOI,优点在这里就不详细介绍了,下面进入正题. public int Import(string path) { IList<Studen ...
- java学习之i/o
基本的输入输出 这里有两种方法,其中一种被注释了,可以换着注释后测试一遍 class TestSystem { public static void main(String[] args) { /* ...
- css系列教程--margin padding column(完结)
margin/margin-left/margin-right/margin-top/margin-bottom设置边距属性margin:0;--所有外边距0margin:0 1px;--margin ...
- ASP.NET MVC 常用内置验证特性
1.[Required] : 必须输入 [Required(ErrorMessage = "请输入用户名")] 2.[StringLength] : 限制字符串长度 [String ...
- 使用Zbar实现简单的二维码扫描
导入ZBarSDK导入系统库 AVFoundation.framework,CoreMedia.framework,CoreVideo.framework,QuartzCore.framework,l ...
- HDU 2157 - How many ways??
给图,图中任意可达的两点间步数为1 问从图中A点走到B点步数为k的有几条路 祭出离散数学图论那章中的 邻接矩阵A. 设S=Ak 则 S[a][b] 为 a到b,步数为k的不同路的条数 剩下的就是矩阵快 ...