Add `host`, `basePath` and `schemes` to swagger.json using Swashbuckle Aspnetcore

Jsinh picture Jsinh · Dec 15, 2018 · Viewed 7.9k times · Source

I am using official doc step by step method to configure Swagger UI and generate Swagger JSON file in my ASP.NET core API application.

Get started with Swashbuckle and ASP.NET Core

If I look at my generated swagger.json file - it is missing three important properties host, basePath and schemes

Please help me understand what piece of code can I add so the swagger.json that gets generated will have following mentioned properties/values.

Here is an ideal swagger.json - give attention to the host, basePath and schemes values which are missing if I follow the documentation code in my application

{
  "swagger": "2.0",
  "info": {
    "version": "v1",
    "title": "Demo API Title"
  },
  "host": "some-url-that-is-hosted-on-azure.azurewebsites.net",
  "basePath": "/api",
  "schemes": ["https"],
  "paths": {
    "/Account/Test": {
      "post": {
        "tags": [
          "Admin"
        ],
        "summary": "Account test method - POST",
        "operationId": "AccountTest",
        "consumes": [],
        "produces": [
          "text/plain",
          "application/json",
          "text/json"
        ],
        "parameters": [],
        "responses": {
          "200": {
            "description": "Success",
            "schema": {
              "type": "boolean"
            }
          }
        }
      }
    }
  },
  "definitions": {
    "NumberSearchResult": {
      "type": "object",
      "properties": {
        "number": {
          "type": "string"
        },
        "location": {
          "type": "string"
        }
      }
    }
  },
  "securityDefinitions": {
    "Bearer": {
      "name": "Authorization",
      "in": "header",
      "type": "apiKey",
      "description": "Authorization. Example: \"Authorization: Bearer {token}\""
    }
  },
  "security": [
    {
      "Bearer": []
    }
  ]
}

Answer

Amey Vaidya picture Amey Vaidya · Sep 11, 2019

There are some changes in latest version of Swashbuckle for .netcore

If you wish to change Request URL in Swashbuckle, maybe you are behind API gateway or have custom domain attached to your webapp. Do this.

  1. Create Document filter
public class BasePathDocumentFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            swaggerDoc.Servers = new List<OpenApiServer>() { new OpenApiServer() { Url = "hxxt://yoursite" } };
        }
    }
  1. In your startup file.In services.AddSwaggerGen() method add document filter like this c.DocumentFilter<BasePathDocumentFilter>();