您好,登錄后才能下訂單哦!
這篇文章主要介紹ASP.NET WEB API之屬性路由的示例分析,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
以下為常規(guī)MVC路由
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, );
如果我們要實(shí)現(xiàn)類似以下效果路由的話,使用常規(guī)公約路由比較麻煩。
order/Miles/三只松鼠干果/2袋 order/2017/1/13
如果使用屬性路由的話就比較簡(jiǎn)單了。
新建WEB API項(xiàng)目的話,打開App_Start目錄下的WebApiConfig.cs文件添加以下代碼開啟屬性路由配置。
config.MapHttpAttributeRoutes();
屬性路由也可以和公約路由混合使用,如下:
public static void Register(HttpConfiguration config) { // Web API 配置和服務(wù) // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: new { id=@"\d+"} ); }
在要使用屬性路由的方法上打上特性標(biāo)記,如下 :
[Route("order/{UserNickName}/{ProductName}/{count}")]
測(cè)試結(jié)果(URL經(jīng)過了編碼,不然會(huì)報(bào)400錯(cuò)誤。)
通常情況下,在同一個(gè)控制器中的所有路由以相同的前綴開頭
[Route("api/books")] [Route("api/books/{id:int}")] [Route("api/books")]
這樣很明顯是比較麻煩的。所以我們用[RoutePrefix]屬性來設(shè)置一個(gè)公共的前綴
測(cè)試結(jié)果
如果使用了[RoutePrefix]的話,某些比較特殊的api,我們可以使用波浪線來重寫路由前綴,如下:
測(cè)試結(jié)果(同一個(gè)類下)
路由前綴中也可以包含參數(shù),如下
測(cè)試結(jié)果
可以在路由中添加參數(shù)約束,如下
測(cè)試結(jié)果
如果參數(shù)不是Int類型,則不會(huì)匹配到該路由
以下都是一些會(huì)被支持到的約束
可以使用多個(gè)約束,但是要用冒號(hào)分開
[Route("users/{id:int:length(1,3)}")] public User GetUserById(int id) { ... }
結(jié)果
如果不在范圍內(nèi)的話則匹配不到
自定義路由約束,需要實(shí)現(xiàn)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; } }
注冊(cè)約束
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參數(shù)和默認(rèn)值
你可以通過添加一個(gè)問號(hào)標(biāo)記路由參數(shù)使成為一個(gè)可選的URI參數(shù)。如果一個(gè)路由參數(shù)是可選的,你必須為這個(gè)方法參數(shù)定義一個(gè)默認(rèn)值。
public class BooksController : ApiController { [Route("api/books/locale/{lcid:int?}")] public IEnumerable<Book> GetBooksByLocale(int lcid = 1033) { ... } }
或者在路由模版中定義默認(rèn)值
public class BooksController : ApiController { [Route("api/books/locale/{lcid=1033}")] public IEnumerable<Book> GetBooksByLocale(int lcid) { ... } }
以上是“ASP.NET WEB API之屬性路由的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。