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 APIASP.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 

[csharp] view plaincopy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Web.Http;  
  6.   
  7. namespace MvcApplication1.Controllers  
  8. {  
  9.     public class ValuesController : ApiController  
  10.     {  
  11.         // GET /api/values  
  12.         public IEnumerable<string> Get()  
  13.         {  
  14.             return new string[] { "value1", "value2" };  
  15.         }  
  16.   
  17.         // GET /api/values/5  
  18.         public string Get(int id)  
  19.         {  
  20.             return "value";  
  21.         }  
  22.   
  23.         // POST /api/values  
  24.         public void Post(string value)  
  25.         {  
  26.         }  
  27.   
  28.         // PUT /api/values/5  
  29.           
  30.         public void Put(int id, string value)  
  31.         {  
  32.         }  
  33.   
  34.         // DELETE /api/values/5  
  35.         public void Delete(int id)  
  36.         {  
  37.         }  
  38.     }  
  39. }  

在 Global.cs 中,注册了 Api 的 Url Map: api/{controller}/{id} 每个"Action"是通过 Http谓词(GET/POST/PUT/DELETE)映射的。

[csharp] view plaincopy
 
  1. public static void RegisterRoutes(RouteCollection routes)  
  2. {  
  3.     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.   
  5.     routes.MapHttpRoute(  
  6.         name: "DefaultApi",  
  7.         routeTemplate: "api/{controller}/{id}",  
  8.         defaults: new { id = RouteParameter.Optional }  
  9.     );  
  10.   
  11.     routes.MapRoute(  
  12.         name: "Default",  
  13.         url: "{controller}/{action}/{id}",  
  14.         defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
  15.     );  
  16. }  


(2) 增加一个自定义 Model

[csharp] view plaincopy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace MvcApplication1.Models  
  7. {  
  8.     public class Task  
  9.     {  
  10.         public string Id { get; set; }  
  11.         public string Title { get; set; }  
  12.         public string Content { get; set; }  
  13.         public int Status { get; set; }  
  14.     }  
  15. }  

(3) 增加一个自定义 Repository

[csharp] view plaincopy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using MvcApplication1.Models;  
  6.   
  7. namespace MvcApplication1.Repositories  
  8. {  
  9.     public class TaskRepository  
  10.     {  
  11.         private List<Task> _tasks;  
  12.   
  13.         public TaskRepository()  
  14.         {  
  15.             _tasks = new List<Task> {   
  16.                 new Task { Id="T001", Title="title1", Content="content1" },  
  17.                 new Task { Id="T002", Title="title2", Content="content2" },  
  18.                 new Task { Id="T003", Title="title3", Content="content3" },  
  19.                 new Task { Id="T004", Title="title4", Content="content4" },  
  20.             };  
  21.         }  
  22.   
  23.         public IEnumerable<Task> GetAll()  
  24.         {  
  25.             return _tasks;    
  26.         }  
  27.   
  28.         public Task FindById(string id)  
  29.         {  
  30.             return _tasks.FirstOrDefault(t => t.Id == id);  
  31.         }  
  32.   
  33.         public void Add(Task task)  
  34.         {  
  35.             _tasks.Add(task);  
  36.         }  
  37.   
  38.         public void RemoveById(string id)  
  39.         {  
  40.             var task = _tasks.FirstOrDefault(t => t.Id == id);  
  41.             if (task != null)  
  42.                 _tasks.Remove(task);  
  43.         }  
  44.     }  
  45. }  

(4) 增加 TaskController

[csharp] view plaincopy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Web.Http;  
  6. using MvcApplication1.Models;  
  7.   
  8. namespace MvcApplication1.Controllers  
  9. {  
  10.     public class TasksController : ApiController  
  11.     {  
  12.         private Repositories.TaskRepository _taskRepository = new Repositories.TaskRepository();  
  13.   
  14.         // GET /api/tasks  
  15.         public IQueryable<Task> Get()  
  16.         {  
  17.             return _taskRepository.GetAll().AsQueryable();  
  18.         }  
  19.   
  20.         // GET /api/tasks/5  
  21.         public Task Get(string id)  
  22.         {  
  23.             return _taskRepository.FindById(id);  
  24.         }  
  25.   
  26.         // POST /api/tasks  
  27.         public void Post(Task task)  
  28.         {  
  29.             _taskRepository.Add(task);  
  30.         }  
  31.   
  32.         // DELETE /api/tasks/5  
  33.         public void Delete(string id)  
  34.         {  
  35.             _taskRepository.RemoveById(id);  
  36.         }  
  37.     }  
  38. }  

运行:


同样,客户端可以通过 Http Header 的 Accept 指定返回数据的格式。默认是支持:appliction/xml 和 application/json 
当想返回比如 image/jpeg 这样的图片格式时,需要添加 MediaTypeFormatter 

比如:当指定某个 Task 时,通过指定 Accept : image/jpeg 获取该 Task 的图片信息。

[csharp] view plaincopy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http.Formatting;  
  5. using System.Web;  
  6. using MvcApplication1.Models;  
  7.   
  8. namespace MvcApplication1.Repositories  
  9. {  
  10.     public class TaskPictureFormatter : MediaTypeFormatter  
  11.     {  
  12.         protected override bool CanWriteType(Type type)  
  13.         {  
  14.             return (type == typeof(Task));  
  15.         }  
  16.   
  17.         public TaskPictureFormatter()  
  18.         {  
  19.             SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg"));  
  20.         }  
  21.   
  22.         protected override System.Threading.Tasks.Task OnWriteToStreamAsync(Type type, object value,   
  23.                            System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders,   
  24.                            FormatterContext formatterContext, System.Net.TransportContext transportContext)  
  25.         {  
  26.             var task = value as Task;  
  27.             if (task != null)  
  28.             {  
  29.                 var data = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/TaskImages/" + task.Id + ".png"));  
  30.                 return stream.WriteAsync(data, 0, data.Length);  
  31.             }  
  32.             else  
  33.             {  
  34.                 throw new HttpException((int)System.Net.HttpStatusCode.NotFound, "task is not found", null);  
  35.             }  
  36.         }  
  37.     }  
  38. }  

注意:当找不到对应的图片时,抛出 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
[csharp] view plaincopy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Web.Http;  
  7. using System.Web.Http.SelfHost;  
  8.   
  9. namespace WebApiSelfHostTest  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             var config = new HttpSelfHostConfiguration("http://localhost:8080");  
  16.   
  17.             config.Routes.MapHttpRoute(  
  18.                 "API Default", "api/{controller}/{id}",  
  19.                 new { id = RouteParameter.Optional });  
  20.   
  21.             using (HttpSelfHostServer server = new HttpSelfHostServer(config))  
  22.             {  
  23.                 server.OpenAsync().Wait();  
  24.   
  25.                 Console.WriteLine("HttpServer is opening, Press Enter to quit.");  
  26.                 Console.ReadLine();  
  27.             }  
  28.         }  
  29.     }  
  30.   
  31.     public class Product  
  32.     {  
  33.         public int Id { get; set; }  
  34.         public string Name { get; set; }  
  35.         public decimal Price { get; set; }  
  36.     }  
  37.   
  38.     public class ProductsController : ApiController  
  39.     {  
  40.         public IEnumerable<Product> GetAllProducts()  
  41.         {  
  42.             return new List<Product>   
  43.             {  
  44.                 new Product() { Id = 1, Name = "Gizmo 1", Price = 1.99M },  
  45.                 new Product() { Id = 2, Name = "Gizmo 2", Price = 2.99M },  
  46.                 new Product() { Id = 3, Name = "Gizmo 3", Price = 3.99M }  
  47.             };  
  48.         }  
  49.     }  
  50. }  


原文地址:https://www.cnblogs.com/panpeng666/p/4403050.html