Add a Custom header parameter to .NET Core API in SwaggerOpenAPI

Add header parameter to NET Core API in Swagger

In this article, we will learn how to add a custom header parameter to .NET Core API in Swagger (OpenAPI) documentation.

Today in this article, we will cover below aspects,

Custom headers are helpful when you want to add metadata to your API requests or responses or when you need specific headers for authentication, security, or other purposes.

Documenting custom headers in Swagger ensures that developers consuming your API understand the header requirements and can use the API effectively.

In Swagger/OpenAPI, you can document and define custom headers to be used in your API requests and responses.

Step1 – Create ASP.NET Core API

Create .NET API application

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>

Approach1 – 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" 
                }
            });
        }

    }

The above logic will be applied globally to all APIs. You can control the same based on each API if required using attribute filter techniques.

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,

Add a Custom header parameter to NET Core API in Swagger

Approach2 – Using FromHeaderAttribute to add a header to swagger

One can also use a declarative approach by using FromHeaderAttribute using FromHeader,

        [HttpPost]
        public IActionResult Weather([FromHeader(Name = "x-CustomHeader2")] string city)
        {
            return Ok();
        }

Let’s view generated swagger,

Add a Custom header parameter to NET Core API in Swagger

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

Please sound off your comments below.

Happy Coding !!

References:



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.



7 thoughts on “How to Add a Header Parameter to .NET Core API in Swagger

  1. As of writing this having the OpenApiSchema Type as “String” breaks the Swagger UI. If you switch to “string” it will work just fine. This is just for anyone who might run into the same issue I did.

    Thanks for the article!

  2. Hi,

    From my experience there’s a difference between using the FromHeaderAttribute and the creating an IOperationFilter. Using the FromHeaderAttribute the framework will verify the header is present before allowing a request to be processed. I don’t see this being the case when using an IOperationFilter.

    Is there a means to tap into the FromHeaderAttribute in order to configure required headers dynamically? I have a requirement where I need to be able to specify a number of headers to be present and also have it noted in the OpenAPI spec.

Leave a Reply

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