Add Swagger UI to a custom .NET Web API

2019-07-25 14:38发布

问题:

I want to integrate Swagger UI into my C# .Net Web API project. This is different from a traditional Web API project where you can install a tool like SwashBuckle, which then picks up the HTTP routes defined in your controller classes and creates the UI.

What I have is a custom implementation which generates the OpenAPI/Swagger 3.0 yaml files for different routes.

I have a route defined in a generic controller file which accepts a variable -

http://localhost:8000/myapp/swagger/{document_name}

where document_name is a variable. My code takes this variable and generates the custom documentation based on this value.

http://localhost:8000/myapp/swagger/sedan
http://localhost:8000/myapp/swagger/suv

In the example above my code would return a different Open API spec for sedan and suv.

As of now the URL simply returns Open API 3.0 YAML spec in plain text. What I want to be able to do is to be able to have this file represented in the Swagger UI similar to this -

http://petstore.swagger.io/

Is this possible? Can I use Swashbuckle for this? Do I need to do a custom implementation to host the Swagger UI? What's the best way?

回答1:

If you already have the OpenAPI/Swagger 3.0 yaml file(s) all you need is the UI and you have a few options:

  • Copy the UI files to your server.
    This will give you the most flexibility, allowing you to customize using the configuration parameters
    You only need the files in the dist folder:
    https://github.com/swagger-api/swagger-ui/tree/master/dist

  • Use the petstore or any other existing UI and pass your file as parameter, like this:
    http://petstore.swagger.io/?url=https://raw.githack.com/heldersepu/hs-scripts/master/swagger/swagger_aws.json