Saturday 2 July 2022

Enable Swagger UI with an .NET 6 API having Custom Routing

 In .NET APIs using swagger for API documentation is really useful to perform API testing and to describe API. We may need to set custom API routing, specially when w deploy the APIs as contianers to Kubernetes, to enable path based routing using ingress such as Nginx. Let's look at steps of setting up custom routing and getting swagger to work with custom routing using a .NET 6 API.

Lets begin with creating a web api with .NET 6. In VS code we can create an empty folder and open it in the terminal to execute the below command to create a .NET core 6.0 API.

dotnet new webapi -f net6.0


Swagger is added by default to the API. If you run it using dotnet run you will be able to access swagger UI with a url of following format.

https://localhost:port/swagger


If you inspect the Program.cs file you will see the swagger is added to to the application. 


Now let's assume we want to run the api as /weather/api/ as starting route in path and run swagger UI with weather/api/swagger. Lets first chage the controller routing.

The controller is currently havng route set as below.



Let's set it to use weather/api as shown below and get method to use forecast as route. However the swagger UI stil does not use the route prefix weather/api.


With the code changed as below,



if (app.Environment.IsDevelopment())
{
    app.UseSwagger(c =>
        c.RouteTemplate = "weather/api/{documentName}/swagger.json"
    );
    app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/weather/api/v1/swagger.json", "Weather API");
            c.RoutePrefix = "weather/api/swagger";
        }
    );
}

Now you will see the swagger UI loads with url weather/api/swagger.



No comments:

Popular Posts