2016-11-10 120 views
6

問題是關於使用Route屬性定義自定義路由。Web API 2路由 - 路由屬性

我知道,在WebApiConfig類,你總是定義的默認路由,

configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}", 
    new { id = RouteParameter.Optional }); 

我不能讓工作是當我想通過另一個參數。我知道我能做到這一點(下面的代碼上面所列默認路由,其下定義):

//configuration.Routes.MapHttpRoute(
    // name: "GetBrandImagePaths", 
    // routeTemplate: "api/{controller}/{id}/{type}"); 

但我寧願,而不是定義在WebApiConfig文件中的所有這些路由,使用自定義的路由。 但是,如果我沒有上面的文件中註釋掉的代碼,我會得到一個404。那裏讓我相信自定義Route甚至沒有被查看。

public class HelperApiController : ApiController 
{ 
    [HttpGet] 
    [Route("api/helperapi/{id}/{type}")] 
    public string GetBrandImages(int id, string type) 
    { 
     ..... 
    } 
} 

我怎麼能有它,所以我可以用在WebApiConfig文件中定義的路由,並定義單個API控制器內部的自定義路線。

請注意,該項目也是一個MVC項目(不只是WebApi)。有什麼我失蹤,做錯了等?我知道有很多帖子定義瞭如何傳遞多個參數,但我認爲我的問題是關於爲什麼一個工作而不是另一個工作的一個更具體的問題。

回答

13

您需要撥打config.MapHttpAttributeRoutes()

這將解析所有Controller類並從屬性派生路由。

我不會混合這與標準路由。

+0

所以,如果我再補充一點呼叫,是否弄亂其他默認路由? (行動結果等)?可以肯定地說,使用'config.MapHttpAttrubteRoutes()'僅適用於直線WebApi項目? –

+0

不,它不會覆蓋手動放入的路線。但是,請不要使用任何路由屬性來修飾這些'Controller'類,否則將會出現重複且可能相沖突的路由。我只使用過WebApi項目的路由屬性,因此無法評論它們與MVC的適用性。 – toadflakz

+0

因此,如果我不裝飾任何其他控制器(非Api)w/Route或RoutePrefix,那麼它們仍然會路由到正確的端點? –

5

Attribute Routing in ASP.NET Web API 2

啓用屬性路由

要啓用屬性的路由,在 配置致電MapHttpAttributeRoutes。此擴展方法在 System.Web.Http.HttpConfigurationExtensions類中定義。

using System.Web.Http; 

namespace WebApplication 
{ 
    public static class WebApiConfig 
    { 
     public static void Register(HttpConfiguration config) 
     { 
      // Web API routes 
      config.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 } 
     ); 
    } 
}