2014-02-06 107 views
1

問題Web API。同屬性的路由

當我創建的方法與實際控制人的路線,通用控制器說: 「API /國家/東西」 ...

當我執行上面的請求,我的代碼得到執行&數據得到返回。

但是,當我嘗試呼叫我的路線在基地控制器上。 E.G:「api/country/code/123」

我得到一個404錯誤。

問題

就如何落實,同時利用屬性的路由通用的路由任何想法?

特定的控制器

[RoutePrefix("Country")] 
public class CountryController : MasterDataControllerBase<Country, CountryDto> 
{ 
    public CountryController(
      IGenericRepository<Country> repository, 
      IMappingService mapper, 
      ISecurityService security) : base(repository, mapper, security) 
      { 
      } 
} 

基地

public class MasterDataControllerBase<TEntity, TEntityDto> : ControllerBase 
    where TEntity : class, ICodedEntity, new() 
    where TEntityDto : class, new() 
{ 
    private readonly IMappingService mapper; 

    private readonly IGenericRepository<TEntity> repository; 

    private readonly ISecurityService security; 

    public MasterDataControllerBase(IGenericRepository<TEntity> repository, IMappingService mapper, ISecurityService security) 
    { 
     this.security = security; 
     this.mapper = mapper; 
     this.repository = repository; 
    } 

    [Route("code/{code}")] 
    public TEntityDto Get(string code) 
    { 
     this.security.Enforce(AccessRight.CanAccessMasterData); 

     var result = this.repository.FindOne(o => o.Code == code); 

     return this.mapper.Map<TEntity, TEntityDto>(result); 
    } 
} 
+0

的可能的複製http://stackoverflow.com/questions/19989023/net-webapi-attribute -routing-and-inheritance/24969829#24969829 – Dejan

回答

3

屬性中的Web API路由不支持Route屬性的繼承。你可以看到Inherited = false這表明,如果你查看RouteAttribute類的定義...

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false, AllowMultiple = true)] 
public sealed class RouteAttribute : Attribute, IDirectRouteFactory, IHttpRouteInfoProvider 
{ ... 

這就解釋了爲什麼你得到404,爲Route屬性有效地消失。

由於屬性不是可繼承的,並且該類是密封的,我不知道是否有辦法通過屬性路由基礎結構來實現此目的。

更新:在Web API團隊成員解釋說,這是一個設計決定,它不是繼承... https://stackoverflow.com/a/19989344/3199781

+1

由於Web API 2.2有可能繼承路由屬性。請參閱http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-22 – Onots