如何为 .Net Core Web API 大摇大摆地设置基本路径 属性

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

我已经在 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"
                ],
                .........

所以我想得到的是:

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

我们还有一些其他 API 不是用 .Net Core 编写的,它通过添加默认路由解决了同样的问题。我试图通过删除 API 控制器

顶部的路由在 .Net 核心上做同样的事情
[Route("api/[Controller]")]

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

使用 IDocumentFilter 你可以修改结果 swagger 定义。
我这里有一些例子:

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

最后我用这个来修复它:

您可以设置 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;
});

Swagger v2.0 中使用了 BasePath 它已被替换为 OpenApi v3.0

中的服务器数组

在 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}" } };
        });
    });