5

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

JVIH
  • 103
  • 1
  • 1
  • 8

3 Answers3

6

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

        };
    });            
}
Silvair L. Soares
  • 1,018
  • 12
  • 28
  • 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. – JVIH May 20 '19 at 16:47
  • Upload a complete testing solution here: https://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" – Silvair L. Soares May 20 '19 at 17:24
  • 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: https://github.com/domaindrivendev/Swashbuckle.AspNetCore, there is support for OpenAPI 3.0. – Silvair L. Soares May 20 '19 at 23:15
  • 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](https://github.com/swagger-api/swagger-ui/issues/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. – JVIH May 21 '19 at 18:25
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)

JVIH
  • 103
  • 1
  • 1
  • 8
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"
    });
Doolali
  • 956
  • 9
  • 13