络腮胡菲菲 发表于 2025-3-16 12:36:48

.NET 9 中 OpenAPI 替代 Swagger 文档天生

https://i-blog.csdnimg.cn/direct/48fd8b45e2dd4430b83af230997053b0.png
        微软已经放弃了对 .NET 9 中 Swagger UI 包 Swashbuckle 的支持。他们声称该项目“不再由社区所有者积极维护”并且“标题尚未得到办理”。
        这意味着当您利用 .NET 9 模板创建 Web API 时,您将不再拥有 UI 来测试您的 API 端点。
        我们将观察是否可以在 .NET 9 中利用 Swagger UI 以及是否有更好的替代方案。
        在本文中,我们将深入探讨微软在 .NET 9 中引入的开放 API 支持。此支持使应用步伐的客户可以方便地明白和编写相应的 API 调用,并轻松与我们的主动 HTTP 客户端代码天生工具(如 Swagger)集成。
什么是开放 API?
        OpenAPI 规范是定义 HTTP API 的广泛继承的标准。它可以帮助开辟人员概述 API 的结构,使其更轻易与客户端和服务器天生器、测试框架、文档体系等工具集成。借助 .NET 9,ASP.NET Core 现在内置了对基于控制器和最小 API 天生 OpenAPI 文档的支持,这要归功于 Microsoft.AspNetCore.OpenApi 包。
如何利用它?
https://i-blog.csdnimg.cn/direct/0fcba3cd563846e18284510d467d2a7a.png
        这是一个基本的 ASP.NET Core 9 项目示例,演示了如何将 OpenAPI 支持集成到 Program.cs 中。我们已经准备好了所需的设置。
    builder.Services.AddOpenApi();//这将添加依赖项
    app.MapOpenApi();//这将注册一个端点
自定义
        以下代码更新 Open API 文档端点路径。始终确保路径遵循约定为“<pathtodocument>.json”。
        app.MapOpenApi("/openapidocument.json");
        下面的代码更新了文档的描述,将授权标头标志为必须,并添加了一个额外的服务器作为文档的一部门。
builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer((document, context, cancellationToken) =>
    {
        document.Info.Description = "This is open api demo";
        // Add when authorization headers are required
        var authComponent = new OpenApiComponents
        {
            Headers = new Dictionary<string, OpenApiHeader>
            {
                { "Authorization", new OpenApiHeader { Required = true } }
            }
        };
        document.Components = authComponent;
        // Add new server if app is available at multiple locations
        document.Servers.Add(new OpenApiServer
        {
            Url = "https://appdev.com/",
            Description = "This is dev server"
        });
        return Task.CompletedTask;
    });
});

以下是我们终极的开放 API JSON,可在“https://localhost:7283/openapidocument.json”上找到。
{
  "openapi": "3.0.1",
  "info": {
    "title": "OpenAPIDemo | v1",
    "description": "This is open api demo",
    "version": "1.0.0"
  },
  "servers": [
    {
      "url": "https://localhost:7283"
    },
    {
      "url": "http://localhost:5196"
    },
    {
      "url": "https://appdev.com/",
      "description": "This is dev server"
    }
  ],
  "paths": {
    "/WeatherForecast": {
      "get": {
        "tags": [
          "WeatherForecast"
        ],
        "operationId": "GetWeatherForecast",
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "text/plain": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/WeatherForecast"
                  }
                }
              },
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/WeatherForecast"
                  }
                }
              },
              "text/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/WeatherForecast"
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "WeatherForecast": {
        "type": "object",
        "properties": {
          "date": {
            "type": "string",
            "format": "date"
          },
          "temperatureC": {
            "type": "integer",
            "format": "int32"
          },
          "temperatureF": {
            "type": "integer",
            "format": "int32"
          },
          "summary": {
            "type": "string",
            "nullable": true
          }
        }
      }
    },
    "headers": {
      "Authorization": {
        "required": true
      }
    }
  },
  "tags": [
    {
      "name": "WeatherForecast"
    }
  ]
}
现在,您可以利用 NSwag.AspNetCore 包或任何其他利用开放 API 规范的包简朴地添加 swagger UI。
对于NSwag.AspNetCore来说,必要添加下面的代码。
app.UseSwaggerUi(config =>
{
    config.DocumentPath = "/openapidocument.json";
});
当您尝试 Swagger UI 时,大多数功能都能按预期正常工作。可能必要进行额外的设置或调整以确保所有设置均按预期工作。
下面是一个参考截图。你可能会注意到上面提到的所有内容都是可见的,包括服务器名称和描述等。
https://i-blog.csdnimg.cn/direct/99c6da8211fe437badd8bdd1e2464135.png
希望这篇文章对您有所帮助。请在评论中分享您的想法,以便更好地利用此软件包。
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。  

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: .NET 9 中 OpenAPI 替代 Swagger 文档天生