How to set base path property in swagger for .Net Core Web API

后端 未结 3 569
离开以前
离开以前 2021-01-02 00:47

i\'ve built a Web API in ASP.Net Core (version 1.1.2) and i use the Swashbuckle.AspNetCore for generating the swagger definition.

below is a part of the automaticall

相关标签:
3条回答
  • 2021-01-02 01:23

    BasePath was used in Swagger v2.0 It has been replaced by the servers array in OpenApi v3.0

    In v5 you have to do this for using OpenApi v3.0:

    var basePath = "/v1";
    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}" } };
            });
        });
    
    0 讨论(0)
  • 2021-01-02 01:25

    Use an IDocumentFilter with that you can modify the result swagger definition.
    I have some examples here:

    https://github.com/heldersepu/SwashbuckleTest/blob/master/Swagger_Test/App_Start/SwaggerConfig.cs#L285

    0 讨论(0)
  • 2021-01-02 01:31

    in the end i used this to fix it:

    you can set the PreSerializeFilters to add both the BasePath and edit the Paths. Thought there would be a more elegant way but this works.

    var basepath = "/api/AppStatus";
    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;
    });
    
    0 讨论(0)
提交回复
热议问题