c# - 从 Swagger (Swashbuckle) 隐藏参数

标签 c# swagger .net-5 swashbuckle

我有一个选择了“启用 OpenAPI 支持”的 C# .NET 5.0 ASP.NET Core Web API 应用程序。我想从 swagger 页面上显示的内容中隐藏下面示例中的 optional 参数。我发现了很多关于隐藏属性或 Controller 的帖子,但这些解决方案似乎都不适用于给定代码中的参数:

[HttpGet]
[Route("search")]
[Authorize]
public async Task<IActionResult> Search(string query, string optional = "")
{
   return OK();
}

最佳答案

您可以创建自定义属性和继承自 Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter 的操作过滤器,以从 swagger.json 生成中排除所需的参数

public class OpenApiParameterIgnoreAttribute : System.Attribute
{
}

public class OpenApiParameterIgnoreFilter : Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter
{
    public void Apply(Microsoft.OpenApi.Models.OpenApiOperation operation, Swashbuckle.AspNetCore.SwaggerGen.OperationFilterContext context)
    {
        if (operation == null || context == null || context.ApiDescription?.ParameterDescriptions == null)
            return;

        var parametersToHide = context.ApiDescription.ParameterDescriptions
            .Where(parameterDescription => ParameterHasIgnoreAttribute(parameterDescription))
            .ToList();

        if (parametersToHide.Count == 0)
            return;

        foreach (var parameterToHide in parametersToHide)
        {
            var parameter = operation.Parameters.FirstOrDefault(parameter => string.Equals(parameter.Name, parameterToHide.Name, System.StringComparison.Ordinal));
            if (parameter != null)
                operation.Parameters.Remove(parameter);
        }
    }

    private static bool ParameterHasIgnoreAttribute(Microsoft.AspNetCore.Mvc.ApiExplorer.ApiParameterDescription parameterDescription)
    {
        if (parameterDescription.ModelMetadata is Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadata metadata)
        {
            return metadata.Attributes.ParameterAttributes.Any(attribute => attribute.GetType() == typeof(OpenApiParameterIgnoreAttribute));
        }

        return false;
    }
}

把它放在你 Controller 的参数里

[HttpGet]
[Route("search")]
[Authorize]
public async Task<IActionResult> Search(string query, [OpenApiParameterIgnore] string optional = "")
{
    return Ok();
}

然后在Status.cs中配置

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API Title", Version = "v1" });
        c.OperationFilter<OpenApiParameterIgnoreFilter>();
    });

关于c# - 从 Swagger (Swashbuckle) 隐藏参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69651135/

相关文章:

c# - 将 Asp.Net Core 3.1 应用程序升级到 .Net 5 后,某些 C# 9 功能不可用

c# - 如何从 C# 方法添加 Razor 标记?

c# - 我们如何在 C# 应用程序中运行 Javascript?

c# - Blazor 使元素在 x 秒后消失

c# - SSIS - 该进程无法访问该文件,因为它正被另一个进程使用

c# - ASP.Net MVC - Swashbuckle 无法识别任何 Controller

java - 在 swagger-ui docker 中更改试用网址

api - ReDoc 是否有类似于 Swagger Editor 的实时编辑器?

c# - 如何在 ASP.NET Web 应用程序中显示 Windows.Form.MessageBox?

c# - VS Code Intellisense 未在 C# 中显示建议