Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 automatically generated swagger definition. i would like to change the paths so it does not include /api/ApiName but it would be included in the basePath which is now /

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

so what i would like to get is:

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

We have some other APIs which are not written in .Net Core and there it fixed the same issue by adding default routes. I tried to do the same on .Net core by removing the route at the top of the API controller

[Route("api/[Controller]")]

and adding it to the Startup.cs. however this did not work. Does anyone have any idea on how to fix this?

like image 275
GeertvdC Avatar asked Jul 26 '17 12:07

GeertvdC


People also ask

What is base API path?

The base path is the initial URL segment of the API, and does not include the host name or any additional segments for paths or operations. It is shared by all operations in the API.


2 Answers

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}" } };
        });
    });
like image 98
Roman Marusyk Avatar answered Oct 05 '22 06:10

Roman Marusyk


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;
});
like image 29
GeertvdC Avatar answered Oct 05 '22 05:10

GeertvdC