Set Default Value of Custom Header in Swagger .NET

Set Default Value of Custom Header in Swagger NET

In this article, we will learn how to Set Default Value of Custom Header in Swagger .NET (OpenAPI) documentation.

Swagger Header usage for developers

By setting a default value for custom headers in Swagger, you enhance the usability, maintainability, and overall experience of your ASP.NET Core API.

It ensures that the API is more robust, less prone to errors, and easier to work with for both developers and consumers.

During API testing and debugging, having a default value for the custom header allows developers to quickly check the API behavior without manually providing the header value each time.

By setting a default value, the API documentation becomes more informative and self-explanatory.

Developers using the API can easily understand the expected behavior of the custom header, even if they don’t provide a value explicitly.

In our last article, we already learned the basics of Adding swagger OpenAPI documentation to ASP.NET Core

Let’s get started…

Create ASP.NET Core API

Create ASP.NET .NET API

Step2: Install the required NuGet package

Using CLI tool

dotnet add package Swashbuckle.AspNetCore

OR

Using PMC(package manager console)

PM> Install-Package Swashbuckle.AspNetCore -Version <version>

Using IOperationFilter to add a header to swagger

Create a custom class with the name of your choice ‘CustomHeaderSwaggerAttribute‘ derived from ‘IOperationFilter‘ and overriding Apply method as below,

  public class CustomHeaderSwaggerAttribute : IOperationFilter
    {
       
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
                operation.Parameters = new List<OpenApiParameter>();

            operation.Parameters.Add(new OpenApiParameter
            {
                Name = "X-CustomHeader",
                In = ParameterLocation.Header,
                Required = true,
                Schema = new OpenApiSchema
                {
                    Type = "string" 
                    Default = new OpenApiString("test-12345")
                }
            });
        }

    }

Update Startup.cs to use OperationFilter

Let’s enable this custom Operation filter in the ConfigureServices method as below,

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title ="MyTestService", Version = "v1", });
                c.OperationFilter<CustomHeaderSwaggerAttribute>();

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);

            });
        }

Please see the swagger OpenAPI documentation below,

Summary

By setting a default value for custom headers in Swagger, you enhance the usability, maintainability, and overall experience of your ASP.NET Core API. It ensures that the API is more robust, less prone to errors, and easier to work with for both developers and consumers.

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *