溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

WEB API中ASP.NET屬性路由的示例分析

發(fā)布時(shí)間:2021-09-14 14:40:15 來源:億速云 閱讀:129 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)WEB API中ASP.NET屬性路由的示例分析的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

以下為常規(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

如果使用屬性路由的話就比較簡單了。

新建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ò)誤。)

WEB API中ASP.NET屬性路由的示例分析

通常情況下,在同一個(gè)控制器中的所有路由以相同的前綴開頭

  [Route("api/books")]
  [Route("api/books/{id:int}")]
  [Route("api/books")]

這樣很明顯是比較麻煩的。所以我們用[RoutePrefix]屬性來設(shè)置一個(gè)公共的前綴

WEB API中ASP.NET屬性路由的示例分析

測(cè)試結(jié)果

WEB API中ASP.NET屬性路由的示例分析

如果使用了[RoutePrefix]的話,某些比較特殊的api,我們可以使用波浪線來重寫路由前綴,如下:

WEB API中ASP.NET屬性路由的示例分析

測(cè)試結(jié)果(同一個(gè)類下)

WEB API中ASP.NET屬性路由的示例分析

路由前綴中也可以包含參數(shù),如下

WEB API中ASP.NET屬性路由的示例分析

測(cè)試結(jié)果

WEB API中ASP.NET屬性路由的示例分析

可以在路由中添加參數(shù)約束,如下

WEB API中ASP.NET屬性路由的示例分析

測(cè)試結(jié)果

WEB API中ASP.NET屬性路由的示例分析

如果參數(shù)不是Int類型,則不會(huì)匹配到該路由

以下都是一些會(huì)被支持到的約束

WEB API中ASP.NET屬性路由的示例分析

可以使用多個(gè)約束,但是要用冒號(hào)分開

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

結(jié)果

WEB API中ASP.NET屬性路由的示例分析

如果不在范圍內(nèi)的話則匹配不到

WEB API中ASP.NET屬性路由的示例分析

自定義路由約束,需要實(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) { ... }
}

感謝各位的閱讀!關(guān)于“WEB API中ASP.NET屬性路由的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI