Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 735
JVIH Avatar asked Apr 22 '19 16:04

JVIH


People also ask

Can we pass header in swagger?

We can optionally override it within individual path items and/or methods. This would be the preferred way to specify your security scheme; and it replaces the header parameter from the first example. Unfortunately, Swagger-UI doesn't offer a text box to control this parameter, at least in my testing so far.

What is difference between NSwag and swashbuckle?

NSwag not only provides the functionality of Swashbuckle (Swagger generation) but also code generators. This way we can avoid incompatibilities and offer more features and a more streamlined toolchain.

What is NSwag JSON?

nswag.json defines a set of parameters required by NSwag for generating client code like input assembly and output file path, as well as other different options allowing to adjust the shape of output code to our needs. The easiest way to generate the manifest file is to use Windows UI application called NSwag Studio.


2 Answers

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

        };
    });            
}
like image 130
Silvair L. Soares Avatar answered Sep 17 '22 19:09

Silvair L. Soares


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)

like image 43
JVIH Avatar answered Sep 17 '22 19:09

JVIH