Search code examples
c#.netkubernetesswaggerasp.net-core-webapi

How can I enable swagger in internal development environmensts that is not local host


I have a .NET 8 WEB API, which has been dockerized and running inside of a container. This container is pushed the the Azure ACR and deployed on to Azure AKS. Functionality wise this is working alright but I would like to enable Swagger UI if someone wants to directly test this out without having to run it through visual studio. Swagger UI works fine when I run it through Visual studio.

To achieve this I added this change from the code

var internalEnv = app.Environment.IsDevelopment() || Environment.GetEnvironmentVariable("Internal_Environment") is "Development";

`if (internalEnv)
{
 Console.Write("Internal is true");

 app.UseSwagger();
 app.UseSwaggerUI();
 }
`

In the deployment yaml file that I use to deploy this to the AKS cluster (development that is) I added this

`        env:
        - name: Internal_Environment
          value: "Development"`

When I check the container log I can see the line "Internal is true" which means app.UseSwagger and app.UseSwaggerUI is called. But the issue is I cannot find the correct url to access the swagger UI.

Typically an endpoint would be specified as follows (a hello end point for example), http://test-dev.abcword.com/api/registration/hello => This works fine So I tried accessing swagger through

http://test-dev.abcword.com/api/registration/swagger/index.html but this gives a 404.

The application is a part of a microservices solution

Any help is much appreciated

Tried adding an environment variable and enabling swagger when that environment variable is present


Solution

  • UPDATE

    var internalEnv = app.Environment.IsDevelopment() || Environment.GetEnvironmentVariable("Internal_Environment") == "Development";
    
    if (internalEnv)
    {
        Console.WriteLine("Internal is true");
        app.UseSwagger(c =>
        {
            c.RouteTemplate = "api/registration/swagger/{documentName}/swagger.json";
        });
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/api/registration/swagger/v1/swagger.json", "My API V1");
            c.RoutePrefix = "api/registration/swagger";
        });
    }
    

    http://test-dev.abcword.com/api/registration/swagger/index.html but this gives a 404.

    The correct url shoud be http://test-dev.abcword.com/swagger/index.html or http://test-dev.abcword.com/swagger.

    And we also can change the default url by using RoutePrefix. Here is the sample code.

    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("../swagger/v1/swagger.json", "Test API V1");
        c.RoutePrefix = string.Empty;// Set Swagger UI at apps root
    });