问题
I am upgrading my api from .netcore2.1 to 3.1
The api uses SwagerUI and Autorest to generate the client.
From this question about Autorest I found out that I need to use
app.UseSwagger(c =>
{
c.SerializeAsV2 = true;
});
However the UI gives
Fetch error
Internal Server Error v1/swagger.json
The json is
{
"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."
}
[Update]
I found mention of it here
c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
{
swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}{pathPrefix}" } };
});
Now the json shows
{
"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."
}
回答1:
The following worked
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}" } };
});
});
来源:https://stackoverflow.com/questions/60813853/microsoft-openapi-models-openapidocument-serializeasv2-invalid-uri-the-format-o