2017-06-12 64 views
2

由於很多屬性都是由設計的,所以避免了未密封的屬性我正在尋找一個解決方案來設置屬性值(我的第一個想法是繼承該類並設置一個構造函數來檢查web -config - 不與密封類可能):動態設置ApiExplorerSettingsAttributes的值

還有的ApiExplorerSettingsAttribute命名空間System.Web.Http.Description

我想下面的API-行動得到隱藏的情況下,在網絡配置的值是假的:

<Api.Properties.Settings> 
    <setting name="Hoster"> 
    <value>False</value> 
    </setting> 
</Api.Properties.Settings> 

的動作應該是這樣的:

[HttpGet, Route("api/bdlg")] 
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(BdlgDataStorage))] 
[ApiExplorerSettings(IgnoreApi = Properties.Settings.Default.Hoster)] 
private async Task<BdlgDataStorage> GetBdlgStorageValues() 
{ 
    using (var context = new BdlgContext()) 
     return context.BdlgDataStorages 
      .Include(s=>s.ChangeTrack) 
      .Where(w=>w.Isle > 56) 
      .Select(selectorFunction) 
      .ToListAsync(); 
} 

的重要行是:

[ApiExplorerSettings(IgnoreApi = Properties.Settings.Default.Hoster)]

在這裏,我得到一個編譯錯誤:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

任何人有任何想法,我可以如何設置IgnoreApi的值與來自web-config的值相同?

回答

3

你不能。屬性靜態編譯到程序集中。它們屬於成員的元數據。您不能在運行時更改屬性。

你必須找到另一種方式來影響ApiExplorerSettings。這篇文章似乎是你正在尋找的:Dynamically Ignore WebAPI method on controller for api explorer documentation

+1

其實,這就是我正在尋找。我只需要檢查它是否也適用於搖擺樂。 –

0

另一種可能的解決方案,我發現是使用預處理指令(這將是足以讓我,因爲操作只應在招搖可見時,它的DEBUG):

#if DEBUG 
    [ApiExplorerSettings(IgnoreApi = true)] 
#else 
    [ApiExplorerSettings(IgnoreApi = false)] 
#endif 
    [SwaggerResponse(HttpStatusCode.OK, Type = typeof(BdlgDataStorage))] 
    [HttpGet, Route("api/bdlg")] 
    private async Task<BdlgDataStorage> GetBdlgStorageValues() 
    { 
     using (var context = new BdlgContext()) 
      return context.BdlgDataStorages 
       .Include(s=>s.ChangeTrack) 
       .Where(w=>w.Isle > 56) 
       .Select(selectorFunction) 
       .ToListAsync(); 
    }