Microsoft.OpenApi.Models.OpenApiDocument.SerializeAsV2 无效 URI:无法确定 URI 的格式

Microsoft.OpenApi.Models.OpenApiDocument.SerializeAsV2 Invalid URI: The format of the URI could not be determined

我正在将我的 API 从 .netcore 2.1 升级到 3.1

API使用SwagerUIAutorest生成客户端。

我发现我需要使用:

app.UseSwagger(c =>
{
    c.SerializeAsV2 = true;
});

然而,UI 给出:

Fetch error
Internal Server Error v1/swagger.json

JSON是:

{
  "StatusCode": 500,
  "ErrorMessage": "Internal server error: Invalid URI: The format of the URI could not be determined. nStack:
    at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
    at Microsoft.OpenApi.Models.OpenApiDocument.WriteHostInfoV2(IOpenApiWriter writer, IList`1 servers)
    at Microsoft.OpenApi.Models.OpenApiDocument.SerializeAsV2(IOpenApiWriter writer)
    at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.RespondWithSwaggerJson(HttpResponse response, OpenApiDocument swagger)
    at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
    at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)",
  "SystemMessage": "Invalid URI: The format of the URI could not be determined."
}

[更新]

我发现有人提到它 here:

c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
{
    swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}{pathPrefix}" } };
});

现在 JSON 显示:

{
  "StatusCode": 500,
  "ErrorMessage": "Internal server error: Invalid URI: Invalid port specified. Stack:
    at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
    at Microsoft.OpenApi.Models.OpenApiDocument.WriteHostInfoV2(IOpenApiWriter writer, IList`1 servers)
    at Microsoft.OpenApi.Models.OpenApiDocument.SerializeAsV2(IOpenApiWriter writer)
    at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.RespondWithSwaggerJson(HttpResponse response, OpenApiDocument swagger)
    at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
    at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)",
  "SystemMessage": "Invalid URI: Invalid port specified."
}

以下有效

        var basePath = "/v1";
        app.UseSwagger(c =>
        {
            c.RouteTemplate = "swagger/{documentName}/swagger.json";
            c.SerializeAsV2 = true;
            c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
            {
                swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}{basePath}" } };
            });

        });