Search code examples
c#swagger.net-5swashbuckle

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();
}

Solution

  • You can create a custom attibute and an operation filter inhering from Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter to exclude the desired parameters from swagger.json generation

    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;
        }
    }
    

    Put it in your controller's parameter

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

    Then configure it in Status.cs

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