Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...
}
like image 312
phunque Avatar asked Oct 03 '18 16:10

phunque


People also ask

What is SwaggerOperation attribute?

SwaggerOperation is a useful attribute where you can set the summary, description, id, and the tags of an individual request/route.

What is swashbuckle C#?

Swashbuckle. AspNetCore. SwaggerUI: an embedded version of the Swagger UI tool. It interprets Swagger JSON to build a rich, customizable experience for describing the web API functionality. It includes built-in test harnesses for the public methods.

What is documentName in swagger?

The {documentName} refers to the name you specify in the AddSwaggerGen() method. The following code uses myapi as the name for a swagger document. builder.Services.AddSwaggerGen(options => options.SwaggerDoc("myapi", new OpenApiInfo { Title = "My API", Version = "v1" }) );


1 Answers

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 });
like image 123
phunque Avatar answered Sep 20 '22 19:09

phunque