1 访问路径属性 Route
public class OrdersController : ApiController
{
[Route("customers/{customerId}/orders")]
[HttpGet]
public IEnumerable<Order> FindOrdersByCustomer(int customerId) { ... }
}
字符串
"customers/{customerId}/orders"是路由模板。 Web API根据这个模板进行匹配。 在这个例子中, "customers" 和 "orders" 是文字描述部分,必须完全匹配, "{customerId}" 是变量部分。
2.HTTP Request 属性
Web API 在选择action时,会基于HTTP的request类型的。
默认的,Web API 会匹配controller方法的开始部分,例如方法名称为PostCustomers 会匹配HTTP的Post request。
我们也可以通过方法修饰属性来控制request类型。
方法修饰属性 :[HttpDelete] [HttpGet] [HttpHead] [HttpOptions] [HttpPatch] [HttpPost] [HttpPut]
[Route("api/books")]
[HttpPost]
public HttpResponseMessage CreateBook(Book book) { ... }
以上代码控制HTTP的request类型为Post.
3.HTTP 方法列表属性 AcceptVerbs
[Route("api/books")]
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public void MakeCollection() { }
以上代码同时支持Get和Post.
4.路由前缀属性 Route Prefixes
[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) { ... }
}
用符号“~”覆盖路由前缀
[RoutePrefix("api/books")]
public class BooksController : ApiController
{
// GET /api/authors/1/books
[Route("~/api/authors/{authorId:int}/books")]
public IEnumerable<Book> GetByAuthor(int authorId) { ... }
// ...
}
5 路由约束
通过路由约束来约束参数类型。语法{参数:字段类型}
[Route("users/{id:int}")]
public User GetUserById(int id) { ... }
[Route("users/{id:int:min(1)}")]
public User GetUserById(int id) { ... }
//有默认值
public class BooksController : ApiController
{
[Route("api/books/locale/{lcid:int=1033}")]
public IEnumerable<Book> GetBooksByLocale(int lcid) { ... }
}
支持的约束类型:
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}$)} |
6 路由名称
在HTTP 调用方法时,可以使用路由名称调用。
[Route("api/books/{id}", Name="GetBookById")]
public BookDto GetBook(int id)
{
// Implementation not shown...
}