动态设置ApiExplorerSettingsAttributes的值

4

由于很多属性都是由避免未封闭的属性设计的,我正在寻找一种解决方案来设置属性值(我的第一个想法是继承类并设置一个构造函数以检查web-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相同吗?
3个回答

4

2
事实上,这就是我一直在寻找的。我只需要检查一下它是否也适用于 Swagger。 - Matthias Burger
你是否学过这是否与Swagger兼容? - Sangman

1
我发现另一个可能的解决方案是使用预处理指令(对我来说这已经足够了,因为该操作只在调试时在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();
    }

0

参考 https://joonasw.net/view/hide-actions-from-swagger-openapi-documentation-in-aspnet-core,我正在为测试操作或控制器执行此操作:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class TestSwaggerAttribute : Attribute { }

public class ActionHidingConvention : IActionModelConvention
{
    private readonly Boolean isDevelopment;

    public ActionHidingConvention(IWebHostEnvironment env)
    {
        isDevelopment = env.IsDevelopment();
    }

    public void Apply(ActionModel action)
    {
        if (!isDevelopment && (
            action.Controller.Attributes.Any(x => x.GetType() == typeof(TestSwaggerAttribute))
            || action.Attributes.Any(x => x.GetType() == typeof(TestSwaggerAttribute))))
            action.ApiExplorer.IsVisible = false;
    }
}

还有在 program.cs 文件中:

builder.Services
    .AddControllers(c =>
    {
        c.Conventions.Add(new ActionHidingConvention(builder.Environment));
    })

例:

[HttpPost, TestSwagger]
public async Task<IActionResult> TestCreateAsync([FromBody] Something info) {...}

或者

[ApiController, Route("api/[controller]", TestSwagger)]
public class ProductController : Controller {...}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接