日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

ASP.NET Web API 中的属性路由

發布時間:2025/3/11 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET Web API 中的属性路由 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

為什么要有屬性路由?

基于約定路由的一個優點是模板在單個位置中定義,并且路由規則在所有控制器上一致的應用。但是基于約定的路由很難支持RESTFUl 中常見的某些URI模式。例如,資源通常包含子資源,客戶有訂單,電影有演員,書有作者等等。創建反應這些URI是很自然的,如下圖所示:

/customers/1/orders

?使用屬性路由,為此URI定義路由很簡單,只需向控制器中添加一個屬性,如下圖所示:

[Route("customers/{customerId}/orders")] public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }

?


啟用屬性路由?

要啟用屬性路由,要在配置期間調用MapHttpAttributeRoutes,此方法在System.Web.Http.HttpConfigurationExtensions類中定義。如下圖所示:?

using System.Web.Http;namespace WebApplication {public static class WebApiConfig{public static void Register(HttpConfiguration config){// Web API routesconfig.MapHttpAttributeRoutes();// Other Web API configuration not shown.}} }

屬性路由可以和約定路由相結合,要定義基于約定的路由,可以調用MapHttpRoute方法。如下圖所示:?

public static class WebApiConfig {public static void Register(HttpConfiguration config){// Attribute routing.config.MapHttpAttributeRoutes();// Convention-based routing.config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional });} }

添加屬性路由?

public class OrdersController : ApiController {[Route("customers/{customerId}/orders")][HttpGet]public IEnumerable<Order> FindOrdersByCustomer(int customerId) { ... } }

字符串“customers/{customerId}/orders”是路徑的URI模板,Web API嘗試將請求URI和模板匹配。在此示例中,“customers”和“orders”是靜態片段,{customerId}是可變參數,以下URI將與此模板匹配:

  • http://localhost/customers/1/orders
  • http://localhost/customers/bob/orders
  • http://localhost/customers/1234-5678/orders

請注意:路由模板中的{customerId}參數要和方法中customerId相匹配,當WebAPI調用控制器操作時,它會嘗試綁定路由參數。例如?URI為 http://example.com/customers/1/orders ,則Web API會嘗試將 值“1”綁定到操作的customerId參數中。

URI模板中可以有多個參數,如下圖所示:

[Route("customers/{customerId}/orders/{orderId}")] public Order GetOrderByCustomer(int customerId, int orderId) { ... }

?

Web API還根據請求的Http方法(Get,Post等)選擇操作。默認情況下,Web API會查找與控制器方法名稱的開頭不區分大小寫的匹配項。例如,控制器方法PutCustomer匹配HTTP PUT請求。?

以下示例將CreateBook方法映射到HTTP POST請求。?

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

對于所有其他HTTP方法(包括非標準方法),請使用AcceptVerbs屬性,該屬性采用HTTP方法列表。?

// WebDAV method [Route("api/books")] [AcceptVerbs("MKCOL")] public void MakeCollection() { }

?


路由前綴?

通常,控制器的中的路由都以相同的前綴開頭,例如:?

public class BooksController : ApiController {[Route("api/books")]public IEnumerable<Book> GetBooks() { ... }[Route("api/books/{id:int}")]public Book GetBook(int id) { ... }[Route("api/books")][HttpPost]public HttpResponseMessage CreateBook(Book book) { ... } }

您可以使用[RoutePrefix]屬性為整個控制器設置公共前綴:?

[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) { ... } }

在method屬性上使用波浪號(?)來覆蓋路由前綴:?

[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) { ... } }

路徑約束允許限制路徑模板中的參數匹配方式。一般語法是“{parameter:constraint}”。例如:?

[Route("users/{id:int}")] public User GetUserById(int id) { ... }[Route("users/{name}")] public User GetUserByName(string name) { ... }

?這時候,只有id是整數時,才匹配第一路徑。否則,將選擇第二路徑。完整的約束列表如下圖所示:

約束描述例子
alpha匹配大寫或者小寫拉丁字母:(a-z , A-Z){x:alpha}
bool匹配布爾類型{x:bool}
datetime匹配DataTime類型{x:datetime}
decimal匹配小數值{x:decimal}
double匹配64位浮點數{x:double}
float匹配32位浮點數{x:float}
guid匹配Guid值{x:guid}
int匹配32位整型{x:int}
length匹配具有指定長度或者具有指定長度范圍的字符串{x:length(6)} {x:length(1,20)}
long匹配64位整數值{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:regex(^\d{3}-\d{3}-\d{4}$)}

可以將多個約束應用于參數,以冒號分隔?

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

?

可以通過實現IHttpRouteConstraint,來創建自定義路由約束。例如,以下約束將參數限制為非零整數值。?

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;} }

以下代碼顯示了如何注冊約束:?

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參數和默認值?

?可以通過向路由參數添加問號來使URI參數可選。如果route參數是可選的,則必須為方法參數定義默認值

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

?在這個例子中,/api/books/locale/1033? 和 /api/books/locale 返回相同的資源。或者可以在路由模板中指定默認值,如下圖所示:

public class BooksController : ApiController {[Route("api/books/locale/{lcid:int=1033}")]public IEnumerable<Book> GetBooksByLocale(int lcid) { ... } }

路由名稱?

在Web API 中,每個路由都有一個名稱。路由名稱對于對于生成鏈接十分有用,因此可以在HTTP響應中包含鏈接。

要指定路由名稱,請在屬性上設置“Name”屬性,以下示例顯示如何設置路由名稱,以及如何在生成的鏈接時使用路由名稱。

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;} }

路由順序?

當框架嘗試將URI與路由匹配時,它會按特定的順序評估路由,要指定順序,需要在Route屬性上設置Order屬性,框架首先評估Order值較低的方法,默認Order值為零。

以下是確定總排序的方式:

1、比較Route屬性的Order屬性。

2、查看路由模板中的每個URI片段,對于細分,約定如下:

? ? ? a、靜態片段。

? ? ? b、使用約束路由參數。

? ? ? c、路由參數沒有約束。

? ? ? d、具有約束的通配符參數段

? ? ? e、沒有約束的通配符參數段

[RoutePrefix("orders")] public class OrdersController : ApiController {[Route("{id:int}")] // constrained parameterpublic HttpResponseMessage Get(int id) { ... }[Route("details")] // literalpublic HttpResponseMessage GetDetails() { ... }[Route("pending", RouteOrder = 1)]public HttpResponseMessage GetPending() { ... }[Route("{customerName}")] // unconstrained parameterpublic HttpResponseMessage GetByCustomer(string customerName) { ... }[Route("{*date:datetime}")] // wildcardpublic HttpResponseMessage Get(DateTime date) { ... } }

以上路由將按以下順序執行:

1、orders/details?

2、orders/{id}

3、orders/{customerName}

4、orders/{*date}

5、orders/pending

?

?

?

?

?

?

?

?

?

?

?

?

總結

以上是生活随笔為你收集整理的ASP.NET Web API 中的属性路由的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。