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中,两种可以共存。
以下是原文的思维导图总结:
代码片段:
怎么启用属性路由?
-
public static class WebApiConfig
-
{
-
public static void Register(HttpConfiguration config)
-
{
-
// Web API 配置和服务
-
// 将 Web API 配置为仅使用不记名令牌身份验证。
-
config.SuppressDefaultHostAuthentication();
-
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
-
-
// Web API 路由
-
config.MapHttpAttributeRoutes(); //此句为关键
-
-
config.Routes.MapHttpRoute(
-
name: "DefaultApi",
-
routeTemplate: "api/{controller}/{id}",
-
defaults: new { id = RouteParameter.Optional}
-
);
-
}
-
}
通过HTTP METHOD和Route属性一起使用
-
[Route("api/books")]
-
[HttpPost]
-
public HttpResponseMessage CreateBook(Book book) { ... }
路由前缀Attribute,用于简化公共部分
-
[RoutePrefix("api/books")]
-
public class BooksController : ApiController
-
{
-
// GET api/books
-
[Route("")]
-
public IEnumerable<Book> Get() { ... }
-
-
// GET api/books/5
-
[Route("{id:int}")]
-
public Book Get(int id) { ... }
-
-
// POST api/books
-
[Route("")]
-
public HttpResponseMessage Post(Book book) { ... }
-
}
参数约束
-
[Route("users/{id:int:min(1)}")]
-
public User GetUserById(int id) { ... }
可选参数
-
public class BooksController : ApiController
-
{
-
[Route("api/books/locale/{lcid:int?}")]
-
//[Route("api/books/locale/{lcid:int=1033}")]
-
public IEnumerable<Book> GetBooksByLocale(int lcid = 1033) { ... }
-
}
为路由指定一个名称
[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 });