根据 API 密钥显示/隐藏 swagger UI 端点

Joe*_*ill 5 .net c# asp.net swagger-ui swashbuckle

我已经设置了 swagger,但它向每个人显示了所有控制器。我只想显示基于 API 密钥权限的控制器,因此他们必须在Exploreswagger 部分输入 API 密钥才能看到任何内容。这可行吗?

Ale*_* I. 3

如果我们谈论Swashbuckle包,那么我们需要使用 Implement IDocumentFilter

您可以从这篇文章中查看一些初步信息。

基本场景:

  • 定义自定义Attribute
  • 将此属性设置为Controllers/Actions
  • DocumentFilter在你的类中实现过滤逻辑

代码示例可在此处获取:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class LicenseValidatorAttribute : Attribute
{
    public FeatureType Feature { get; set; }
}

public class FeatureDocumentFilter : IDocumentFilter
{
    private readonly IFeatureService _featureService;

    public FeatureDocumentFilter(IFeatureService featureService)
    {
        _featureService = featureService;
    }

    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        foreach (var api in context.ApiDescriptions)
        {
            var attribute = api.CustomAttributes().OfType<FeatureValidatorAttribute>().FirstOrDefault();

            if (attribute != null)
            {
                var success = _featureService.ValidateFeature(attribute.Feature);

                if (!success.Valid)
                {
                    var route = "/" + api.RelativePath;
                    swaggerDoc.Paths.Remove(route);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)