【问题标题】:Set the ApiExplorerSettingsAttributes value dynamically动态设置 ApiExplorerSettingsAttributes 值
【发布时间】:2017-06-12 13:42:31
【问题描述】:

由于很多属性是由 avoid unsealed attributes 设计的,我正在寻找设置属性值的解决方案(我的第一个想法是继承类并设置一个构造函数来检查网络-config - 不能使用密封类):

命名空间System.Web.Http.Description中有ApiExplorerSettingsAttribute

我希望在案例中隐藏以下 API 操作,web-config 中的值为 false:

<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)]

在这里,我得到一个编译器错误:

属性参数必须是属性参数类型的常量表达式、typeof表达式或数组创建表达式

任何人都有任何想法,我如何将 IgnoreApi 的值设置为与 web-config 中的值相同?

【问题讨论】:

    标签: c# attributes


    【解决方案1】:

    我发现的另一种可能的解决方案是使用预处理器指令(这对我来说已经足够了,因为只有在 DEBUG 时动作才应该在 swagger 中可见):

    #if DEBUG
        [ApiExplorerSettings(IgnoreApi = false)]
    #else
        [ApiExplorerSettings(IgnoreApi = true)]
    #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();
        }
    

    【讨论】:

      【解决方案2】:

      你不能。属性被静态编译到程序集中。它们属于成员的元数据。您不能在运行时更改属性。

      你必须找到另一种方式来影响ApiExplorerSettings。这篇文章似乎正是您要查找的内容:Dynamically Ignore WebAPI method on controller for api explorer documentation

      【讨论】:

      • 事实上,这就是我一直在寻找的。我只需要检查这是否也适用于招摇。
      猜你喜欢
      • 2012-09-05
      • 1970-01-01
      • 2011-11-03
      • 2012-08-23
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      相关资源
      最近更新 更多