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

JVIH picture JVIH · Apr 22, 2019 · Viewed 8.2k times · Source

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

Answer

JVIH picture JVIH · May 20, 2019

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)