How to set base path property in swagger?

sw
sw
2 Points
1 Posts

I have .NetCore Api application and integrated Swashbuckle.AspNetCore to generating swagger document. I want to set basePath something like:

{
    "swagger": "2.0",
    "info": {
        "version": "v1",
        "title": "ApiName.V1"
    },
    "host": "ApiUrl",
    "basePath": "/api",
    "paths": {
        "/": {
            "get": {
                "tags": [
                    "ApiName"
                ],
                .........

Is there any way to set custome basePath?

Views: 71
Total Answered: 1
Total Marked As Answer: 0
Posted On: 08-Mar-2021 04:13

Share:   fb twitter linkedin
Answers
Brian
Brian
Participant
616 Points
83 Posts
         

Add following in startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

In  Swagger v2.0 with OpenAPi 2.0:

var basepath = "/api";
c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.BasePath = basepath);


c.PreSerializeFilters.Add((swaggerDoc, httpReq) => {
    IDictionary<string, PathItem> paths = new Dictionary<string, PathItem>();
    foreach (var path in swaggerDoc.Paths)
    {
        paths.Add(path.Key.Replace(basepath, "/"), path.Value);
    }
    swaggerDoc.Paths = paths;
});

In v5 with  OpenApi v3.0:

var basePath = "/api";
app.UseSwagger(c =>
    {
        c.RouteTemplate = "swagger/{documentName}/swagger.json";
        c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
        {
            swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}{basePath}" } };
        });
    });

References:

Posted On: 09-Mar-2021 03:34
 Log In to Chat