2017-09-04 24 views
-1

我正在一個mvc Api項目中工作,同時使用[route(「api/MyCont/getspecific」)進行路由操作)我意識到 這將是一個好主意變量來存儲這個控制器的基本路徑:「api/myCont」,所以我可以重用那部分路由,並且使代碼的維護更容易。mvc api路由變量保存基本路徑

這是我的嘗試:

public class MyContController : ApiController 
{ 

    private readonly string BaseRoute="api/MyCont" ; 

    [HttpGet] 
    [Route(BaseRoute+"/GetSpecific")] 
    public IHttpActionResult GetSpecificItem(string ItemId) 
    { 
    /* do something 
    get the item from a source 
    */ 

     return Ok(Item); 
    } 

} 

,但是當我這樣做,沒有在路線錯誤「的對象引用需要非靜態字段,方法或roperty BaseRoute」。

我應該怎麼做才能解決它? 您認爲我在做什麼,在良好實踐方面是一個好主意?

+0

它需要是'const'(未'readonly') –

+4

注意正常的方式是使用'控制器上[RoutePrefix( 「API/MyCont」)]'。請參閱[ASP.NET Web API 2中的屬性路由](https://docs.microsoft.com/zh-cn/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in -web-API-2) –

回答

0

使用下面的代碼中,你使用它的變量應該是靜態的,因爲在RUT中註冊Rout時表達式應該被評估。

 private const string BaseRoute = "api/MyCont"; 
     [HttpGet] 
     [Route(BaseRoute + "/GetSpecific")] 
     public string Helloworld() 
     { 
      return "Hello World"; 
     }