如何在swagger中为.Net Core Web API设置基本路径属性

Gee*_*vdC 8 c# swagger swashbuckle asp.net-core asp.net-core-webapi

我在ASP.Net Core(版本1.1.2)中构建了一个Web API,并使用Swashbuckle.AspNetCore生成swagger定义.

下面是自动生成的swagger定义的一部分.我想改变路径,所以它不包括/ api/ApiName,但它将包含在basePath中,现在是/

{
    "swagger": "2.0",
    "info": {
        "version": "v1",
        "title": "ApiName.V1"
    },
    "host": "ApiUrl",
    "basePath": "/api/ApiName",
    "paths": {
        "/": {
            "get": {
                "tags": [
                    "ApiName"
                ],
                .........
Run Code Online (Sandbox Code Playgroud)

所以我想得到的是:

{
    "swagger": "2.0",
    "info": {
        "version": "v1",
        "title": "ApiName.V1"
    },
    "host": "ApiUrl",
    "basePath": "/",
    "paths": {
        "/api/ApiName": {
            "get": {
                "tags": [
                    "ApiName"
                ],
                .........
Run Code Online (Sandbox Code Playgroud)

我们有一些其他的API没有用.Net Core编写,并且它通过添加默认路由修复了同样的问题.我试图通过删除API控制器顶部的路由在.Net核心上做同样的事情

[Route("api/[Controller]")]
Run Code Online (Sandbox Code Playgroud)

并将其添加到Startup.cs.但是这没用.有没有人知道如何解决这个问题?

Rom*_*syk 14

BasePath 曾在Swagger v2.0中使用 已被OpenApi v3.0 中的 servers 数组取代

在 v5 中,您必须这样做才能使用 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}" } };
        });
    });
Run Code Online (Sandbox Code Playgroud)


Gee*_*vdC 12

最后我用它来修复它:

您可以设置PreSerializeFilters以添加BasePath并编辑路径.以为会有更优雅的方式,但这有效.

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;
});
Run Code Online (Sandbox Code Playgroud)