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

How to add subfolder to requests urls in Swagger in ASP.NET Core Web API?


I have an ASP.NET Core 7 Web API with swagger.

I have the frontend of my application hosted on the root domain and the API hosted in the api folder.

The Swagger UI opens on https:[domain]/api/swagger/index.html but all endpoints in swagger are still on the root directory https:[domain]:

enter image description here

This is causing a http 500 error.

I've tried adding api to the Route in all controller like:

namespace ApiProject.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CompaniesController : ControllerBase
    {
        .....

    }
}

But that is adding additional api in all endpoints. for example : https://[domain]/api/api/companies/getall

How can I add the api subfolder to all Swagger requests without it effecting the endpoints urls?


Solution

  • I solved my issue by adding the subfolder using UseSwagger function as mentioned in this answer, so I've added this code to Program.cs

    app.UseSwagger(options =>
    {
        options.PreSerializeFilters.Add((doc, request) =>
        {
            doc.Servers = new List<OpenApiServer>
            {
                new OpenApiServer { Url = $"{request.Scheme}://{request.Host.Value}/api" } // Add the custom postfix here
            };
        });
    });