5

I'm using ASP.NET Core and NSwag to host and describe a new web service hosted in IIS with Windows Authentication.

Locally I run the web service using https, but when I deploy to a test environment the web service sits behind a load balancer with SSL-offloading. This means that even though the site appears to run under SSL in the browser, the actual binding in IIS is http. So my Swagger UI page (and swagger.json definition) describes the schemes supported as http.

I'd like the Schemes element in the Swagger.json that I use to read "https" instead of "http". Would anyone be able to help me find the property I need to set in my code to set the scheme manually?

{
    x-generator: "NSwag v11.19.1.0 (NJsonSchema v9.10.72.0 (Newtonsoft.Json v11.0.0.0))",
    swagger: "2.0",
    info: {
        title: "My API title",
        description: "Provides access to data.",
        version: "1.0.0"
    },
    host: "myhostname.net",
    schemes: [
        "http"
    ],
    etc...
}
phunque
  • 321
  • 3
  • 13

3 Answers3

14

Boom. Got it!

Finally found an answer on Github and the following code did the trick:

app.UseSwaggerWithApiExplorer(config =>
{
    //...other code omitted...
    config.PostProcess = settings =>
    {
        settings.Schemes.Clear();
        settings.Schemes.Add(NSwag.SwaggerSchema.Https);
    };
});

EDIT:

for NSwag v12 use:

app.UseSwagger(configure => configure.PostProcess = (document, _) => document.Schemes = new[] { SwaggerSchema.Https });
Filip Cornelissen
  • 3,682
  • 3
  • 31
  • 41
phunque
  • 321
  • 3
  • 13
  • 4
    In NSwag version 13, UseSwagger has gone obsolete. We can now user - app.UseOpenApi(configure => configure.PostProcess = (document, _) => document.Schemes = new[] { NSwag.OpenApiSchema.Https }); – darkenergy Nov 28 '19 at 06:50
1

I have the same situation, an ASP.NET Core app published in the cloud behind a proxy with SSL offloading. I didn't want to make changes to the local environment, and I found this solution - force HTTPS on the production environment only (NSwag 13+):

app.UseOpenApi(config => config.PostProcess = (document, request) =>
{
  if (env.IsProduction())
  {
    document.Schemes = new[] { NSwag.OpenApiSchema.Https };
  }
});
pfedotovsky
  • 711
  • 2
  • 10
  • 23
-1

My project was using NSwag v13 and the below worked for me.

app.UseOpenApi(a => {
    a.PostProcess = (document, _) => {
        document.Schemes = new[] { OpenApiSchema.Https, OpenApiSchema.Http };
    };
});

Source: https://github.com/RicoSuter/NSwag/issues/1545

Saiteja Samala
  • 111
  • 2
  • 7