Search code examples
.net-coreminimal-apisfast-endpoints

Fast-endpoints global headers in swagger for all endpoints


I am using fast-endpoints library for building a minimal API. I need to have two generic headers (name, tracking-Id) across all methods of all the resources.

To implement this requirement, I have used a custom implementation of IGlobalPreProcessor which checks if the incoming requests have these headers. It sends out a validation failure message if the headers are not present.

However on the swagger page, I don't see these two headers. I need help to add these two headers on swagger.

I have tried to implement IOperationProcessor, but not sure how to use it with fast-endpoints as builder.services.AddOpenApiDocument() is called inside fast-endpoints extension builder.Services.SwaggerDocument()


Solution

  • you can register an IOperationProcessor like this with FastEndpoints:

    builder.Services.SwaggerDocument(o =>
    {
        o.DocumentSettings = s => s.OperationProcessors.Add(new AddCustomHeader());
    });
    

    and here's an example processor that adds a custom header to the swagger doc globally:

    internal sealed class AddCustomHeader : IOperationProcessor
    {
        public bool Process(OperationProcessorContext context)
        {
            var hdrParameter = new OpenApiParameter()
            {
                Name = "x-custom",
                Kind = OpenApiParameterKind.Header,
                IsRequired = true,
                Type = JsonObjectType.String,
                Default = "xyz",
                Description = "The description of the field"
            };
    
            context.OperationDescription.Operation.Parameters.Add(hdrParameter);
    
            return true;
        }
    }