简体   繁体   中英

ASP.NET Core 3.1 AWS Lambda Swagger definition not working when deployed

Having the below code to configure in Startup.cs

Variables.

private const string SwaggerDocumentVersionName = "v1";
private static string SwaggerDocumentServiceName => $"Users API({SwaggerDocumentVersionName})";

ConfigureServices method.

services.AddSwaggerGen(c =>
{
   c.SwaggerDoc(
         SwaggerDocumentVersionName, 
               new OpenApiInfo
               {
                   Title = SwaggerDocumentServiceName,
                   Version = $"{SwaggerDocumentVersionName}"
               });
});

Configure method.

app.UseSwagger(c =>
{
    c.RouteTemplate = "/swagger/{documentName}/swagger.json";
});

app.UseSwaggerUI(c =>
{
    c.RoutePrefix = "swagger/ui";
    c.SwaggerEndpoint($"/swagger/{SwaggerDocumentVersionName}/swagger.json", SwaggerDocumentServiceName);
});

When running locally ( https://localhost:5001/swagger/ui resolved to https://localhost:5001/swagger/ui/index.html ) definition is loaded correctly and everything seems fine.

Deploying the service to AWS Lambda as ASP.NET Core REST API and navigating to the URL ( https://DNS_URL/API_PREFIX/swagger/ui resolved to https://DNS_URL/API_PREFIX/swagger/ui/index.html )it shows the below error loading the JSON definition.

Swagger JSON 定义错误

The interesting part is that if you navigate to the JSON definition route ( https://DNS_URL/API_PREFIX/swagger/v1/swagger.json ) it shows the definition.

The main URL for the API you have released on lambda is https://DNS_URL/API_PREFIX/

Swagger UI needs to fetch the swagger.json file in order for it to work, and for your localhost it is working correctly since https://localhost:5001/swagger/v1/swagger.json is a valid endpoint

(*you have no prefix here)

And the version deployed to lambda is trying to fetch this swagger.json file under

https://DNS_URL/swagger/v1/swagger.json - without your API_PREFIX , thus it's returning 404, not found and swagger ui is displaying the Error message.

Quick fix, which you might apply, that I think would work:

app.UseSwaggerUI(c =>
{
    c.RoutePrefix = "swagger/ui";
    c.SwaggerEndpoint($"{env.IsDevelopment() ? "" : API_PREFIX}/swagger/{SwaggerDocumentVersionName}/swagger.json", SwaggerDocumentServiceName);
});

Where the API_PREFIX is a string starting with '/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM