WebApi2官网学习记录---Attribute Routing
从WebApi 1迁移到WebAPI 2要改变配置代码如下:
WebApi 1:
protected void Application_Start()
{
// WARNING - Not compatible with attribute routing.
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
WebAPI 2:
protected void Application_Start()
{
// Pass a delegate to the Configure method.
GlobalConfiguration.Configure(WebApiConfig.Register);
}
添加一个Route Attributes
public class OrdersController : ApiController
{
[Route("customers/{customerId}/orders")]
[HttpGet]
public IEnumerable<Order> FindOrdersByCustomer(int customerId) { ... }
}
可以匹配一下URL:
- http://localhost/customers/1/orders
- http://localhost/customers/bob/orders
- http://localhost/customers/1234-5678/orders
匹配http post请求的CreateBook
[Route("api/books")]
[HttpPost]
public HttpResponseMessage CreateBook(Book book) { ... }
[Route("api/books")]
[AcceptVerbs("MKCOL")]
public void MakeCollection() {
Route Prefixes
对于同一个controller路由有相同的前缀, 此时可以使用 [RoutePrefix] 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) { ... }
}
可以在方法的attribute中使用(~)重写路由前缀
[RoutePrefix("api/books")]
public class BooksController : ApiController
{
// GET /api/authors/1/books
[Route("~/api/authors/{authorId:int}/books")]
public IEnumerable<Book> GetByAuthor(int authorId) { ... } // ...
}
路由前缀中可以包含参数
[RoutePrefix("customers/{customerId}")]
public class OrdersController : ApiController
{
// GET customers/1/orders
[Route("orders")]
public IEnumerable<Order> Get(int customerId) { ... }
}
路由约束
路由约束用于严格匹配路由中的参数,通用语法是{参数:约束},如下:
[Route("users/{id:int}"]
public User GetUserById(int id) { ... } [Route("users/{name}"]
public User GetUserByName(string name) { ... }
支持的约束如下表所示:
Constraint | Description | Example |
---|---|---|
alpha | Matches uppercase or lowercase Latin alphabet characters (a-z, A-Z) | {x:alpha} |
bool | Matches a Boolean value. | {x:bool} |
datetime | Matches a DateTime value. | {x:datetime} |
decimal | Matches a decimal value. | {x:decimal} |
double | Matches a 64-bit floating-point value. | {x:double} |
float | Matches a 32-bit floating-point value. | {x:float} |
guid | Matches a GUID value. | {x:guid} |
int | Matches a 32-bit integer value. | {x:int} |
length | Matches a string with the specified length or within a specified range of lengths. | {x:length(6)} {x:length(1,20)} |
long | Matches a 64-bit integer value. | {x:long} |
max | Matches an integer with a maximum value. | {x:max(10)} |
maxlength | Matches a string with a maximum length. | {x:maxlength(10)} |
min | Matches an integer with a minimum value. | {x:min(10)} |
minlength | Matches a string with a minimum length. | {x:minlength(10)} |
range | Matches an integer within a range of values. | {x:range(10,50)} |
regex | Matches a regular expression. | {x:regex(^\d{3}-\d{3}-\d{4}$)} |
注意:带括号的约束,如"min",可以对路由中的参数应用多个约束,用冒号分割约束
[Route("users/{id:int:min(1)}")]
public User GetUserById(int id) { ... }
自定义路由约束
public class NonZeroConstraint : IHttpRouteConstraint
{
public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,
IDictionary<string, object> values, HttpRouteDirection routeDirection)
{
object value;
if (values.TryGetValue(parameterName, out value) && value != null)
{
long longValue;
if (value is long)
{
longValue = (long)value;
return longValue != ;
} string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
if (Int64.TryParse(valueString, NumberStyles.Integer,
CultureInfo.InvariantCulture, out longValue))
{
return longValue != ;
}
}
return false;
}
} 修改WebAPIConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var constraintResolver = new DefaultInlineConstraintResolver();
constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint)); config.MapHttpAttributeRoutes(constraintResolver);
}
} 实际应用:
[Route("{id:nonzero}")]
public HttpResponseMessage GetNonZero(int id) { ... }
可选的URI参数和默认值
第一种方式,默认值直接分配给了方法参数,因此参数获得的是精确的值
第二种方式,默认值通过model-binding进行处理,默认的model-binder将字符串类型的默认值"1033"转为int形的1033,对于model-binder可能有所不同。
第一种写法
public class BooksController : ApiController
{
[Route("api/books/locale/{lcid:int?}")]
public IEnumerable<Book> GetBooksByLocale(int lcid = ) { ... }
} 第二种写法
public class BooksController : ApiController
{
[Route("api/books/locale/{lcid:int=1033}")]
public IEnumerable<Book> GetBooksByLocale(int lcid) { ... }
}
Route Names
web api中每个路由有一个name,Route names可以用来生成links
public class BooksController : ApiController
{
[Route("api/books/{id}", Name="GetBookById")]
public BookDto GetBook(int id)
{
// Implementation not shown...
} [Route("api/books")]
public HttpResponseMessage Post(Book book)
{
// Validate and add book to database (not shown) var response = Request.CreateResponse(HttpStatusCode.Created); // Generate a link to the new book and set the Location header in the response.
string uri = Url.Link("GetBookById", new { id = book.BookId });
response.Headers.Location = new Uri(uri);
return response;
}
}
Route Order
通过设置RouteOrder属性在route attribute上,可以指定Route的顺序,值越小先被计算,默认顺序对应的值是0
路由顺序的选择:
- 比较RouteOrder属性
- 对于URI部分按如下进行排序
- URI的固定部分(literal segments)
- 带约束的路由参数
- 不带约束的路由参数
- 带约束的通配符
- 不带约束的通配符
- route的排序不区分大小写的
[RoutePrefix("orders")]
public class OrdersController : ApiController
{
[Route("{id:int}")] // constrained parameter
public HttpResponseMessage Get(int id) { ... } [Route("details")] // literal
public HttpResponseMessage GetDetails() { ... } [Route("pending", RouteOrder = )]
public HttpResponseMessage GetPending() { ... } [Route("{customerName}")] // unconstrained parameter
public HttpResponseMessage GetByCustomer(string customerName) { ... } [Route("{*date:datetime}")] // wildcard
public HttpResponseMessage Get(DateTime date) { ... }
}
路由排序如下:
- orders/{details}
- orders/{id}
- orders/{customreName}
- orders/{*date}
- orders/pending
Route Attribute的使用完整例子:
using BooksAPI.DTOs;
using BooksAPI.Models;
using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description; namespace BooksAPI.Controllers
{
[RoutePrefix("api/books")]
public class BooksController : ApiController
{
private BooksAPIContext db = new BooksAPIContext(); // Typed lambda expression for Select() method.
private static readonly Expression<Func<Book, BookDto>> AsBookDto =
x => new BookDto
{
Title = x.Title,
Author = x.Author.Name,
Genre = x.Genre
}; // GET api/Books
[Route("")]
public IQueryable<BookDto> GetBooks()
{
return db.Books.Include(b => b.Author).Select(AsBookDto);
} // GET api/Books/5
[Route("{id:int}")]
[ResponseType(typeof(BookDto))]
public async Task<IHttpActionResult> GetBook(int id)
{
BookDto book = await db.Books.Include(b => b.Author)
.Where(b => b.BookId == id)
.Select(AsBookDto)
.FirstOrDefaultAsync();
if (book == null)
{
return NotFound();
} return Ok(book);
} [Route("{id:int}/details")]
[ResponseType(typeof(BookDetailDto))]
public async Task<IHttpActionResult> GetBookDetail(int id)
{
var book = await (from b in db.Books.Include(b => b.Author)
where b.AuthorId == id
select new BookDetailDto
{
Title = b.Title,
Genre = b.Genre,
PublishDate = b.PublishDate,
Price = b.Price,
Description = b.Description,
Author = b.Author.Name
}).FirstOrDefaultAsync(); if (book == null)
{
return NotFound();
}
return Ok(book);
} [Route("{genre}")]
public IQueryable<BookDto> GetBooksByGenre(string genre)
{
return db.Books.Include(b => b.Author)
.Where(b => b.Genre.Equals(genre, StringComparison.OrdinalIgnoreCase))
.Select(AsBookDto);
} [Route("~api/authors/{authorId}/books")]
public IQueryable<BookDto> GetBooksByAuthor(int authorId)
{
return db.Books.Include(b => b.Author)
.Where(b => b.AuthorId == authorId)
.Select(AsBookDto);
} [Route("date/{pubdate:datetime:regex(\\d{4}-\\d{2}-\\d{2})}")]
[Route("date/{*pubdate:datetime:regex(\\d{4}/\\d{2}/\\d{2})}")]
public IQueryable<BookDto> GetBooks(DateTime pubdate)
{
return db.Books.Include(b => b.Author)
.Where(b => DbFunctions.TruncateTime(b.PublishDate)
== DbFunctions.TruncateTime(pubdate))
.Select(AsBookDto);
} protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
其中以下路由中的匹配符*的作用:
[Route("date/{pubdate:datetime:regex(\\d{4}-\\d{2}-\\d{2})}")]
[Route("date/{pubdate:datetime:regex(\\d{4}/\\d{2}/\\d{2})}")] // new
public IQueryable<BookDto> GetBooks2(DateTime pubdate)
{
/*
* 路由中的*匹配符的作用,是为了告诉route engine占位符{pubdate}应该匹配剩余的URI,
* 默认情况下,一个模板参数仅仅匹配一个URI。
* This tells the routing engine that {pubdate} should match the rest of the URI. By default,
* a template parameter matches a single URI segment. In this case, we want {pubdate} to
* span several URI segments:
*/ }
WebApi2官网学习记录---Attribute Routing的更多相关文章
- WebApi2官网学习记录---Configuring
Configuration Settings WebAPI中的configuration settings定义在HttpConfiguration中.有一下成员: DependencyResolver ...
- WebApi2官网学习记录---Cookie
Cookie的几个参数: Domain.Path.Expires.Max-Age 如果Expires与Max-Age都存在,Max-Age优先级高,如果都没有设置cookie会在会话结束后删除cook ...
- WebApi2官网学习记录---批量处理HTTP Message
原文:Batching Handler for ASP.NET Web API 自定义实现HttpMessageHandler public class BatchHandler : HttpMess ...
- WebApi2官网学习记录---Html Form Data
HTML Forms概述 <form action="api/values" method="post"> 默认的method是GET,如果使用GE ...
- WebApi2官网学习记录--HttpClient Message Handlers
在客户端,HttpClient使用message handle处理request.默认的handler是HttpClientHandler,用来发送请求和获取response从服务端.可以在clien ...
- WebApi2官网学习记录--HTTP Message Handlers
Message Handlers是一个接收HTTP Request返回HTTP Response的类,继承自HttpMessageHandler 通常,一些列的message handler被链接到一 ...
- WebApi2官网学习记录--- Authentication与Authorization
Authentication(认证) WebAPI中的认证既可以使用HttpModel也可以使用HTTP message handler,具体使用哪个可以参考一下依据: 一个HttpModel可以 ...
- WebApi2官网学习记录---单元测试
如果没有对应的web api模板,首先使用nuget进行安装 例子1: ProductController 是以硬编码的方式使用StoreAppContext类的实例,可以使用依赖注入模式,在外部指定 ...
- WebApi2官网学习记录---Tracing
安装追踪用的包 Install-Package Microsoft.AspNet.WebApi.Tracing Update-Package Microsoft.AspNet.WebApi.WebHo ...
随机推荐
- Create new Android Virtual Device时不能创建
在Create new Android Virtual Device时不能创建... 因为之前有重装过系统,ADT和java都没有更换,不知道是不是有哪里的环境(C盘中的配置)出错了... LOG在下 ...
- DG下手工处理v$archive_gap方法
从9i以后,oracle dataguard 备库一般都不需要手工处理丢失的日志,FAL自动会帮我们处理,下面通过个案例来讲下手工处理丢失的日志的方法: 1.在备库查询有哪些日志丢失,没应用到备库 S ...
- 自己手动绿色化MyEclipse
绿化过程因每个人的文件存放路径不同而不同 首先打开你解压的MyEclipse文件,或者以前安装的MyEclipse重装系统后不能用,打开到这里:记住路径,比如我的是:D:\MyEclipse 我们打开 ...
- POJ 模拟题集合
http://www.cppblog.com/Uriel/articles/101592.html 感觉这个暑假没有去年有激情啊,,,还没到状态就已经块上学了,,, 真是弱暴了,,,找几道模拟题刷刷. ...
- [leetcode][042] Trapping Rain Water (Java)
我在Github上新建了一个解答Leetcode问题的Project, 大家可以参考, 目前是Java 为主,里面有leetcode上的题目,解答,还有一些基本的单元测试,方便大家起步. 题目在这里: ...
- sql语句各种九九乘法表
下面用while 和 if 条件写的SQL语句的四种九九乘法表 --9x9 左下角 ) BEGIN SET @S='' WHILE @J<=@I BEGIN )))))) END PRINT @ ...
- 你不了解PHP的10件事情
看到有人翻译的<10 things you (probably) didn’t know about PHP>,发现在此次之前2.8两条并不知道,1.3虽然熟知但是去没有实际应用. 由于阅 ...
- ie6兼容性
文本重复Bug 在IE6中,一些隐藏的元素(如注释.display:none;的元素)被包含在一个浮动元素里,就有可能引发文本重复bug.解决办法:给浮动元素添加display:inline;. 躲猫 ...
- BeanUtils框架浅析
一.使用步骤: 1.添加jar包: commons-beanutils-1.8.0.jar commons-logging.jar 2.使用setProperty()方法对javabean设置属性值 ...
- 对C标准中空白字符(空格、回车符(\r)、换行符(\n)、水平制表符(\t)、垂直制表符(\v)、换页符(\f))的理解
版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[+] C标准库里<ctype.h>中声明了一个函数: int isspace(int c); 该函数判断字符c是否 ...