JVIH
JVIH

Reputation: 123

How to add custom headers in NSwag document using C# .NET CORE?

I am in need of adding custom headers, but cannot figure it out. I am trying to utilize the new services.AddOpenApiDocument() instead of the services.AddSwaggerDocument(). I want to add these custom headers on my whole API not just a single method or controller. I attempted to add an operation processor, but when I load up the swagger UI I receive the following error "😱 Could not render this component, see the console."

Here is my snippet within my ConfigureServices():

    services.AddOpenApiDocument(document =>
    {
        ...
        // this works fine
        document.OperationProcessors.Add(new OperationSecurityScopeProcessor("Bearer"));
        document.DocumentProcessors.Add(new SecurityDefinitionAppender("Bearer", new SwaggerSecurityScheme
            {
                Type = SwaggerSecuritySchemeType.ApiKey,
                Name = "Authorization",
                In = SwaggerSecurityApiKeyLocation.Header
            })
        );

        // this is the header i want to show up for all endpoints that is breaking
        document.OperationProcessors.Add(new SampleHeaderOperationProcessor());
    });

Here is my operation processor:

public class SampleHeaderOperationProcessor : IOperationProcessor
{
    public Task<bool> ProcessAsync(OperationProcessorContext context)
    {
        context.OperationDescription.Operation.Parameters.Add(
            new SwaggerParameter {
                Name = "Sample",
                Kind = SwaggerParameterKind.Header,
                Type = NJsonSchema.JsonObjectType.String,
                IsRequired = false,
                Description = "This is a test header",
                Default = "{{\"field1\": \"value1\", \"field2\": \"value2\"}}"
            });

        return Task.FromResult(true);
    }
}

The only thing I have pertaining to this within my Configure():

    app.UseSwagger();
    app.UseSwaggerUi3();                              

Here is my error and the console log: My error and console log

If it helps I'm using ASP .NET CORE 2.2 and NSwag.AspNetCore v12.1.0

Upvotes: 7

Views: 19794

Answers (4)

Arbak
Arbak

Reputation: 11

Do not forget add app.UseOpenApi() in Configuration (in Program.cs) in order to render header parameter using AddOpenApiDocument approach,

Refer: https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-nswag?view=aspnetcore-8.0&tabs=visual-studio

Upvotes: 0

Doolali
Doolali

Reputation: 1006

A big thanks to the original answers on this thread.

I had to do a few small updates to the above answers due to NSwag updates.

The below works for me on versions (NSwag.Core: 13.1.2, NJsonSchema: 10.0.24):

context.OperationDescription.Operation.Parameters.Add(
    new OpenApiParameter
    {
        Name = "HEADER_NAME",
        Kind = OpenApiParameterKind.Header,
        Schema = new JsonSchema { Type = JsonObjectType.String },
        IsRequired = true,
        Description = "Description",
        Default = "Default Value"
    });

Upvotes: 6

JVIH
JVIH

Reputation: 123

This finally worked for me. Solution directly from Rico Suter,

Try

Schema = new JsonSchema4 { Type = NJsonSchema.JsonObjectType.String }

instead of

Type = NJsonSchema.JsonObjectType.String

(I think Type is deprecated in OpenAPI 3)

Upvotes: 5

Silvair L. Soares
Silvair L. Soares

Reputation: 1066

Here's an example I've implemented in a project. For me here, it's working normally:

enter image description here

Implementation of the interface "IOperationProcessor":

using NSwag;
using NSwag.SwaggerGeneration.Processors;
using NSwag.SwaggerGeneration.Processors.Contexts;
using System.Threading.Tasks;

namespace api.mstiDFE._Helpers.Swagger
{
    public class AddRequiredHeaderParameter : IOperationProcessor
    {
        public Task<bool> ProcessAsync(OperationProcessorContext context)
        {
            context.OperationDescription.Operation.Parameters.Add(
            new SwaggerParameter
            {
                Name = "token",
                Kind = SwaggerParameterKind.Header,
                Type = NJsonSchema.JsonObjectType.String,
                IsRequired = false,
                Description = "Chave de acesso à API, fornecida pela RevendaCliente",
                Default = "Default Value"
            });

            return Task.FromResult(true);
        }
    }
}

Reference in startup.cs:

internal static void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{

    // Register the Swagger services
    services.AddSwaggerDocument(config =>
    {
        // Adds the "token" parameter in the request header, to authorize access to the APIs
        config.OperationProcessors.Add(new AddRequiredHeaderParameter());

        config.PostProcess = document =>
        {
            document.Info.Version = "v1";
            document.Info.Title = "Title ";
            document.Info.Description = "API para geração de Documentos Fiscais Eletrônicos (DF-e) do projeto SPED";
            document.Info.TermsOfService = "None";
            document.Info.Contact = new NSwag.SwaggerContact
            {
                Name = "Name",
                Email = "Email ",
                Url = "Url "
            };
            document.Info.License = new NSwag.SwaggerLicense
            {
                Name = "Use under LICX",
                Url = "https://example.com/license"
            };

        };
    });            
}

Upvotes: 8

Related Questions