简体   繁体   中英

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

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...
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM