c# - Hide parameter from Swagger (Swashbuckle)
问题描述
I have a C# .NET 5.0 ASP.NET Core Web API application with "Enable OpenAPI support" selected. I want to hide the optional
parameter in the below example from what shows up on the swagger page. I have found numerous posts about hiding a property or the controller but none of these solutions seem to work for just the parameter in the given code:
[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;
}
}
将其放入控制器的参数中
[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>();
});
推荐阅读
- vba - 使用 VBA 将多个 Outlook 电子邮件保存到驱动器
- python-3.x - 密码学解密问题
- python - 在具有 DateTime 索引的 Pandas DataFrame 中查找每天第一次和最后一次出现的值的索引位置
- r - 从列表中提取值和属性并将它们转换为 R 中的数据框
- python - 如何在 Reportlab 中根据来自不同文档的信息生成 pdf?
- bash - 从远程 ssh 服务器上的 tar 存档中提取某些文件
- reactjs - 每次显示组件时如何调用函数?
- c++ - 用于获取 ARM 时钟频率的 C++ 内联 ASM 代码
- css - 为什么通用/通配符选择器上的悬停伪选择器似乎不适用?
- javascript - 我应该如何使用 decodeuri 组件?