How do I specify the "scheme" element using NSwag and C#?
Asked Answered
T

3

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...
}
Trumpery answered 3/10, 2018 at 16:48 Comment(0)
T
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 });
Trumpery answered 3/10, 2018 at 19:59 Comment(1)
In NSwag version 13, UseSwagger has gone obsolete. We can now user - app.UseOpenApi(configure => configure.PostProcess = (document, _) => document.Schemes = new[] { NSwag.OpenApiSchema.Https });Hardfeatured
K
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 };
  }
});
Kaslik answered 25/2, 2023 at 18:51 Comment(0)
I
-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

Istria answered 12/4, 2022 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.