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

4

7

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

Dunstan answered 22/4, 2019 at 16:19 Comment(0)
D
5

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)

Dunstan answered 20/5, 2019 at 17:33 Comment(0)
L
8

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"
            };

        };
    });            
}
Locklear answered 16/5, 2019 at 12:51 Comment(4)
The difference I see between your code and mine is that you are using services.AddSwaggerDocument() which generates documentation in Swagger v2.0 (which your code does work), but I'm trying to leverage the new services.AddOpenApiDocument to generate OAS v3.0 which is breaking for me.Dunstan
Upload a complete testing solution here: github.com/silvairsoares/.NET_Core But I did a test here, swapping "services.AddSwaggerDocument" with "services.AddOpenApiDocument" and the following message was displayed in Swager UI: "Could not render this component, see the console." Apparently there is a problem with the "services.AddOpenApiDocument" statement. Is there any special reason for you to use NSwag? Otherwise you could try using the "Swashbuckle"Locklear
If you need, I have a complete example of Swagger implementation with "Swashbuckle". Where I also included a custom parameter in the header. For what I researched here: github.com/domaindrivendev/Swashbuckle.AspNetCore, there is support for OpenAPI 3.0.Locklear
Hey Silvair, thanks for the response. I ended up posting the solution to my problem which was given to me by Rico Suter. I created an issue for the Swagger UI project in hopes that they can address the non-descriptive error: issue 5366. Also, at the time of writing this I believe Swashbuckle is still in pre-release for their open API spec which is why I'm leveraging NSwag.Dunstan
D
5

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)

Dunstan answered 20/5, 2019 at 17:33 Comment(0)
A
5

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"
    });
Axle answered 8/10, 2019 at 14:8 Comment(0)
H
0

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

Hawkes answered 25/5 at 19:51 Comment(1)
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From ReviewChelyuskin

© 2022 - 2024 — McMap. All rights reserved.