WebApi 2:属性路由 [Route()],attribute routing

 

原文:http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

属性路由,attribute routing,是web api 2 提供的,而早期的称为约定路由, convention-based routing。在web api 2中,两种可以共存。

 

以下是原文的思维导图总结:

 

代码片段:

怎么启用属性路由?

  1. public static class WebApiConfig
  2. {
  3.     public static void Register(HttpConfiguration config)
  4.     {
  5.         // Web API 配置和服务
  6.         // 将 Web API 配置为仅使用不记名令牌身份验证。
  7.         config.SuppressDefaultHostAuthentication();
  8.         config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
  9.  
  10.         // Web API 路由
  11.         config.MapHttpAttributeRoutes();   //此句为关键
  12.  
  13.         config.Routes.MapHttpRoute(
  14.             name: "DefaultApi",
  15.             routeTemplate: "api/{controller}/{id}",
  16.             defaults: new { id = RouteParameter.Optional}
  17.         );
  18.     }
  19. }

 

通过HTTP METHOD和Route属性一起使用

  1. [Route("api/books")]
  2. [HttpPost]
  3. public HttpResponseMessage CreateBook(Book book) { ... }

 

路由前缀Attribute,用于简化公共部分

  1. [RoutePrefix("api/books")]
  2. public class BooksController : ApiController
  3. {
  4.     // GET api/books
  5.     [Route("")]
  6.     public IEnumerable<Book> Get() { ... }
  7.  
  8.     // GET api/books/5
  9.     [Route("{id:int}")]
  10.     public Book Get(int id) { ... }
  11.  
  12.     // POST api/books
  13.     [Route("")]
  14.     public HttpResponseMessage Post(Book book) { ... }
  15. }

 

参数约束

  1. [Route("users/{id:int:min(1)}")]
  2. public User GetUserById(int id) { ... }

 

可选参数

  1. public class BooksController : ApiController
  2. {
  3.     [Route("api/books/locale/{lcid:int?}")]
  4. //[Route("api/books/locale/{lcid:int=1033}")]
  5.     public IEnumerable<Book> GetBooksByLocale(int lcid = 1033) { ... }
  6. }

 

为路由指定一个名称

[Route("api/books/{id}", Name="GetBookById")]

// Generate a link to the new book and set the Location header in the response.

string uri = Url.Link("GetBookById", new { id = book.BookId });

 

 

posted @ 2015-10-23 16:14  _DN  阅读(805)  评论(0编辑  收藏  举报