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更新一个大对象中的某个字断,这才意识到我以前都没有用 ...
随机推荐
- pom.xml详解(转)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...
- 加载本地html遇到的问题
之前要做一个Demo,需要用UIWebView来加载网页,前端的同事把资源包给我,里面包含html,css,JavaScript,图片等文件.我想当然的把文件夹拷到工程中,然后用以下方法加载: NSU ...
- sqlplus常用操作命令2
常用编辑命令:A[ppend] text 将text附加到当前行之后C[hange] /old /new 将当前行中的old替换为newCLear] buff[er] 清除缓冲区中的所有行DEL 删除 ...
- linux中curl命令
linux curl是一个利用URL规则在命令行下工作的文件传输工具.它支持文件的上传和下载,所以是综合传输工具,但按传统,习惯称url为下载工具. 一,curl命令参数,有好多我没有用过,也不知道翻 ...
- 转:C#: static关键字的作用
tatic意思是静态,可以修饰类.字段.属性.方法 标记为static的就不用创建实例对象调用了,可以通过类名直接点出来 static三种用法: 1.用于变量前,表示每次重新使用该变量所在方法.类或自 ...
- CDZSC_2015寒假新人(1)——基础 f
Description An inch worm is at the bottom of a well n inches deep. It has enough energy to climb u i ...
- java学习:AWT组件和事件处理的笔记(1)--菜单条,菜单,菜单项
菜单放在菜单条里,菜单项放在菜单里1.MenuBar 在java.awt包中,负责创建菜单条,即MenuBar的一个实例,便是一个菜单条. 在Frame类中的setMenuBar(Menu ...
- python bool值要注意的一些地方
1.像(),[],{}这三个是可以通过bool(()),bool([]),bool({})转化为bool值的:且它们转化后的结果为False.但是这三个值它本身并不等于False.切记不可以与Fals ...
- android--graphics
Color类 Constants |____BLACK, BLUE, CYAN Methods |____argb,rgb,alpha, red, green, blue |____parseColo ...
- U盘开发之SSD对比
U盘因其小巧方便,逐步取代了笨重的移动硬盘和光驱,成为最普及的存储介质.现在的主板BIOS也将支持USB启动,作为标准之一,再过几年,光驱时代可能就要终结了.从早期的16MU盘,到现在动辄几个G,U盘 ...