zoukankan      html  css  js  c++  java
  • 【ASP.NET】 Web Api (.NET 4.5)

    在刚刚发布的 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

    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.     publicclass ValuesController : ApiController 
    9.     { 
    10.         // GET /api/values 
    11.         public IEnumerable<string> Get() 
    12.         { 
    13.             returnnewstring[] { "value1", "value2" }; 
    14.         } 
    15.  
    16.         // GET /api/values/5 
    17.         publicstring Get(int id) 
    18.         { 
    19.             return"value"
    20.         } 
    21.  
    22.         // POST /api/values 
    23.         publicvoid Post(string value) 
    24.         { 
    25.         } 
    26.  
    27.         // PUT /api/values/5 
    28.          
    29.         publicvoid Put(int id, string value) 
    30.         { 
    31.         } 
    32.  
    33.         // DELETE /api/values/5 
    34.         publicvoid Delete(int id) 
    35.         { 
    36.         } 
    37.     } 

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

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

    (2) 增加一个自定义 Model

    1. using System; 
    2. using System.Collections.Generic; 
    3. using System.Linq; 
    4. using System.Web; 
    5.  
    6. namespace MvcApplication1.Models 
    7.     publicclass Task 
    8.     { 
    9.         publicstring Id { get; set; } 
    10.         publicstring Title { get; set; } 
    11.         publicstring Content { get; set; } 
    12.         publicint Status { get; set; } 
    13.     } 

    (3) 增加一个自定义 Repository

    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.     publicclass TaskRepository 
    9.     { 
    10.         private List<Task> _tasks; 
    11.  
    12.         public TaskRepository() 
    13.         { 
    14.             _tasks = new List<Task> {  
    15.                 new Task { Id="T001", Title="title1", Content="content1" }, 
    16.                 new Task { Id="T002", Title="title2", Content="content2" }, 
    17.                 new Task { Id="T003", Title="title3", Content="content3" }, 
    18.                 new Task { Id="T004", Title="title4", Content="content4" }, 
    19.             }; 
    20.         } 
    21.  
    22.         public IEnumerable<Task> GetAll() 
    23.         { 
    24.             return _tasks;   
    25.         } 
    26.  
    27.         public Task FindById(string id) 
    28.         { 
    29.             return _tasks.FirstOrDefault(t => t.Id == id); 
    30.         } 
    31.  
    32.         publicvoid Add(Task task) 
    33.         { 
    34.             _tasks.Add(task); 
    35.         } 
    36.  
    37.         publicvoid RemoveById(string id) 
    38.         { 
    39.             var task = _tasks.FirstOrDefault(t => t.Id == id); 
    40.             if (task != null
    41.                 _tasks.Remove(task); 
    42.         } 
    43.     } 

    (4) 增加 TaskController

    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.     publicclass TasksController : ApiController 
    10.     { 
    11.         private Repositories.TaskRepository _taskRepository = new Repositories.TaskRepository(); 
    12.  
    13.         // GET /api/tasks 
    14.         public IQueryable<Task> Get() 
    15.         { 
    16.             return _taskRepository.GetAll().AsQueryable(); 
    17.         } 
    18.  
    19.         // GET /api/tasks/5 
    20.         public Task Get(string id) 
    21.         { 
    22.             return _taskRepository.FindById(id); 
    23.         } 
    24.  
    25.         // POST /api/tasks 
    26.         publicvoid Post(Task task) 
    27.         { 
    28.             _taskRepository.Add(task); 
    29.         } 
    30.  
    31.         // DELETE /api/tasks/5 
    32.         publicvoid Delete(string id) 
    33.         { 
    34.             _taskRepository.RemoveById(id); 
    35.         } 
    36.     } 

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

    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.     publicclass TaskPictureFormatter : MediaTypeFormatter 
    10.     { 
    11.         protectedoverridebool CanWriteType(Type type) 
    12.         { 
    13.             return (type == typeof(Task)); 
    14.         } 
    15.  
    16.         public TaskPictureFormatter() 
    17.         { 
    18.             SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg")); 
    19.         } 
    20.  
    21.         protectedoverride System.Threading.Tasks.Task OnWriteToStreamAsync(Type type, object value,  
    22.                            System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders,  
    23.                            FormatterContext formatterContext, System.Net.TransportContext transportContext) 
    24.         { 
    25.             var task = value as Task; 
    26.             if (task != null
    27.             { 
    28.                 var data = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/TaskImages/" + task.Id + ".png")); 
    29.                 return stream.WriteAsync(data, 0, data.Length); 
    30.             } 
    31.             else 
    32.             { 
    33.                 thrownew HttpException((int)System.Net.HttpStatusCode.NotFound, "task is not found", null); 
    34.             } 
    35.         } 
    36.     } 

    注意:当找不到对应的图片时,抛出 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
    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.     class Program 
    11.     { 
    12.         staticvoid Main(string[] args) 
    13.         { 
    14.             var config = new HttpSelfHostConfiguration("http://localhost:8080"); 
    15.  
    16.             config.Routes.MapHttpRoute( 
    17.                 "API Default", "api/{controller}/{id}"
    18.                 new { id = RouteParameter.Optional }); 
    19.  
    20.             using (HttpSelfHostServer server = new HttpSelfHostServer(config)) 
    21.             { 
    22.                 server.OpenAsync().Wait(); 
    23.  
    24.                 Console.WriteLine("HttpServer is opening, Press Enter to quit."); 
    25.                 Console.ReadLine(); 
    26.             } 
    27.         } 
    28.     } 
    29.  
    30.     publicclass Product 
    31.     { 
    32.         publicint Id { get; set; } 
    33.         publicstring Name { get; set; } 
    34.         publicdecimal Price { get; set; } 
    35.     } 
    36.  
    37.     publicclass ProductsController : ApiController 
    38.     { 
    39.         public IEnumerable<Product> GetAllProducts() 
    40.         { 
    41.             returnnew List<Product>  
    42.             { 
    43.                 new Product() { Id = 1, Name = "Gizmo 1", Price = 1.99M }, 
    44.                 new Product() { Id = 2, Name = "Gizmo 2", Price = 2.99M }, 
    45.                 new Product() { Id = 3, Name = "Gizmo 3", Price = 3.99M } 
    46.             }; 
    47.         } 
    48.     } 

    转载自CSND

  • 相关阅读:
    asp.net core 不依赖autofac实现aop
    C# 获取调用者信息
    IIS 命令学习
    Jenkins + PowerShell + .net core 自动打包
    gogs 自定义配置
    搜索文件内容神器:SearchMyFiles
    非常强大的磁盘计算大小工具:TreeSizeFree
    rancher入门教程
    IQueryable 表达式解析学习
    Sql server 入门权威指南
  • 原文地址:https://www.cnblogs.com/houzhitong/p/2383998.html
Copyright © 2011-2022 走看看