Vaptsarov
Vaptsarov

Reputation: 86

Add custom header to all Swagger responses in .Net

We are having WebApi server with Swagger for documenting the endpoints. We want to add Content-Security-Policy and X-Frame-Options headers. We wanted to achieve this by intercepting the calls and adding the custom headers, however we are unable to find a way to do so. We are using Swashbuckle Swagger for WebApi NuGet package with 5.0.4 version.

Is there a way to intercept Swagger responses or any way for adding custom header to the responses?

Upvotes: 3

Views: 2312

Answers (1)

strickt01
strickt01

Reputation: 4048

If you wanted to add the headers to all responses one option would be to add a DelegatingHandler that could add the headers in by overriding the SendAsync method. So you would create a class that inherits from DelegatingHandler and then override SendAsync. e.g.:

public class AddCustomHeadersResponseHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
         var response = await base.SendAsync(request, cancellationToken);

         response.Headers.Add("Content-Security-Policy", "yourSecurityValue");

         response.Headers.Add("X-Frame-Options", "yourFrameOptions");

         return response;
    }
}

Then add an instance of the class to your configuration in Application_Start() in Global.asax.cs:

GlobalConfiguration.Configuration.MessageHandlers.Add(new AddCustomHeadersResponseHandler()); 

Upvotes: 5

Related Questions