[Route("customers/{customerId}/orders")]
[HttpGet]
public IEnumerable<Order> FindOrdersByCustomer(int customerId)
{
return Database.GetOrdersByCustomerId(customerId);
}

比如我們希望是這樣的格式:http://localhost/api/customers/1/orders
[RoutePrefix("api")]
public class OrdersController : ApiController
{
[Route("customers/{customerId}/orders")]
[HttpGet]
public IEnumerable<Order> FindOrdersByCustomer(int customerId)
{
return Database.GetOrdersByCustomerId(customerId);
}
}

在Route特性中使用~來重寫Action的前綴規則
[RoutePrefix("api")]
public class OrdersController : ApiController
{
[Route("~/myapi/customers/{customerId:int}/orders")]
[HttpGet]
public IEnumerable<Order> FindOrdersByCustomer(int customerId)
{
return Database.GetOrdersByCustomerId(customerId);
}
}

RoutePrefix特性定義的前綴還可以帶參數變量:
[RoutePrefix("api/{customerId}")]
public class OrdersController : ApiController
路由約束
可以通過"{參數變量名稱:約束}"來約束路由中的參數變量。
[Route("users/{id:int}"]
public User GetUserById(int id) { ... }
[Route("users/{name}"]
public User GetUserByName(string name) { ... }
以上,如果片段變量id為int類型,就路由到第一個Action,如果不是,路由到第二個Action。
ASP.NET Web API內置約束包括:
alpha,必須為大小寫字母(a-z,A-Z),如:{x:alpha};
bool,必須為布爾值,如:{x:bool}
datetime,必須為DateTime(時間和日期)類型,如:{x:datetime}
decimal,必須為decimal類型,如:{x:decimal}
double,必須為64bit浮點數,如:{x:double}
float,必須為32bit浮點數,如:{x:float}
guid,必須為GUID,如:{x:guid}
int,必須為32bit整數,如:{x:int}
length,字符串長度必須為指定值或者在指定范圍內,如:{x:length(6)} {x:length(1,20)}
long,必須為64bit整數,如:{x:long}
max,小於等於指定值的整數,如:{x:max(10)}
maxlength,字符串長度小於等於指定值,如:{x:maxlength(10)}
min,大於等於指定值的整數整數,如:{x:min(10)}
minlength,字符串長度大於等於指定值,如:{x:minlength(10)}
range,必須是給定范圍內的整數,如:{x:range(10,50)}
regex,必須與正則表達式匹配,如:{x:(^\d{3}-\d{3}-\d{4}$)}
可以為一個參數變量同時設置多個約束:
[Route("api/{id:int:min(1)}")]
實現IHttpRouteConstraint接口,可自定義約束規則。實現一個不能為0的約束。
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 != 0;
}
string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
if (Int64.TryParse(valueString, NumberStyles.Integer,
CultureInfo.InvariantCulture, out longValue))
{
return longValue != 0;
}
}
return false;
}
}
在App_Start文件夾中的WebApiConfig中注冊自定義約束。
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}")]
可選參數及其默認值
第— 種方式:將對應的參數定義成可缺省參數 ,那么它將直接使用可缺省參數的默認值作為路由變量的默認值。
采用這種定義方式的可缺省 由變量名需要添加 “?” 后綴 ,在方法接的地方設置默認值。

另一種方式就是將默認值直接定義在路由模板中,語法
1:可缺省路由變量后加“=”,即默認為空

給路由設置名稱
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("menu", Name = "mainmenu")]
public ActionResult MainMenu() { ... }
//你可以使用 Url.RouteUrl 來生成相應的 URL:
<a href="@Url.RouteUrl("mainmenu")">Main menu</a>
路由優先順序
Route特性設置的路由優先順序是根據慣例和RouteOrder屬性來確定的。
慣例是:
1、靜態片段變量
2、帶約束的片段變量
3、不帶約束的片段變量
4、帶約束的通配符片段變量
5、不帶約束的通配符片段變量
RouteOrder屬性的默認值是0,屬性值越小,排在越前面。
[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 = 1)]
public HttpResponseMessage GetPending() { ... }
[Route("{customerName}")] // unconstrained parameter
public HttpResponseMessage GetByCustomer(string customerName) { ... }
[Route("{*date:datetime}")] // wildcard
public HttpResponseMessage Get(DateTime date) { ... }
}
以上,路由的優先順序是:
orders/details 靜態片段變量,RouteOrder屬性值為0
orders/{id} 帶約束的片段變量,RouteOrder屬性值為0
orders/{customerName} 不帶約束的片段變量,RouteOrder屬性值為0
orders/{*date} 帶約束的通配符片段變量,RouteOrder屬性值為0
orders/pending RouteOrder屬性值為1
參考:http://www.th7.cn/Program/net/201410/302571.shtml

