swaggerswashbuckleswashbuckle.aspnetcore

Hide a header from being displayed in Swagger Swashbuckle


As I already have a common authorization added how do I remove separate(authorization header) from each and every API as shown in the image link below?

swaggerHub_Link


Solution

  • I figured it out:

    You can simply create a custom attibute and an operation filter inhering from Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter in order to hide the header from being displayed in swagger.json

    public class OpenApiHeaderIgnoreAttribute : System.Attribute
    {
    }
    

    class name should end with the name of the base class.

    public class OpenApiHeaderIgnoreFilter : 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(OpenApiHeaderIgnoreAttribute));
            }
    
            return false;
        }
    }
    

    and set this filter class in your startup class configureServices method as below:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSwaggerGen(c =>
        {
            c.OperationFilter<OpenApiHeaderIgnoreFilter>();
        }
    }
    

    and also update your API method in controller as below:

    [EnableQuery]
    [SwaggerOperation(Tags = new[] { "Odata" })]
    public async Task<IActionResult> Get([OpenApiHeaderIgnore] [FromHeader(Name = ClaimNames.AccessToken)] string token)
    {
    // code
    }