首页 > 解决方案 > 在 AWS API Gateway -> Lambda 函数中重新调整流?

问题描述

我使用 AWS api 网关创建了一个 API,例如https://api.mydomain.com/v1/download?id=1234". download资源有GET方法。该GET方法是lambda使用Lambda Proxy Integration.

Lambda 函数需要充当代理。它需要根据标头解析正确的后端端点x-clientId,然后将请求转发到该后端端点并按原样返回响应。所以需要通用处理不同内容类型的 GET 请求。

我的 lambda 函数看起来像(.NET Core)

public async Task<APIGatewayProxyResponse> Route(APIGatewayProxyRequest input, ILambdaContext context)
{
    var clientId = headers["x-clientId"];            
    var mappings = new Mappings();
    var url = await mappings.GetBackendUrl(clientId, input.Resource);       

    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync(url);
    response.EnsureSuccessStatusCode();

    var proxyResponse = new APIGatewayProxyResponse()
    {
        Headers = new Dictionary<string, string>(),
        StatusCode = (int)System.Net.HttpStatusCode.OK,
        IsBase64Encoded = false,
        Body = await response.Content.ReadAsString())
    };            
}

只要请求和响应content-typeapplication/jsonor ,上面的处理程序就可以工作application/xml。但是我不确定后端返回流时如何处理响应。

对于下载 API,后端返回Content-Disposition: attachment; filename="somefilename,ContentType 可能是以下之一:
application/pdf
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/x-zip-compressed
application/octet-stream

对于这些流,我该如何设置APIGatewayProxyResponse.Body

对于 Excel 文件,我尝试如下设置正文

    var proxyResponse = new APIGatewayProxyResponse()
    {
        Headers = new Dictionary<string, string>(),
        StatusCode = (int)System.Net.HttpStatusCode.OK,
        IsBase64Encoded = true,
        Body = Convert.ToBase64String(await response.Content.ReadAsByteArrayAsync())
    };  

proxyResponse.Headers.Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
proxyResponse.Headers.Add("Content-Disposition", "attachment; filename=\"Report.xlsx\"");

当我从浏览器访问 URL 并尝试打开文件时。我收到错误

Excel cannot open the file报告.xlsxbecuase the file format or file extension is not valid. Verify that the file has not been corrupted and that the extention matches the format of the file

我认为问题是我如何设置响应主体

更新 1
因此基于API Gateway 现在支持的AWS doc二进制数据。现在根据文档

您可以指定是否希望 API Gateway 传递集成请求和响应主体,将它们转换为文本(Base64 编码),或将它们转换为二进制(Base64 解码)。这些选项可用于 HTTP、AWS 服务和 HTTP 代理集成。对于目前仅支持 JSON 的 Lambda 函数和 Lambda 函数代理集成,请求正文始终转换为 JSON。

我正在使用目前支持 JSON 的 Lambda 函数代理。但是,此处的示例显示了如何使用 Lambda 代理来实现。
我认为我在这里缺少的是二进制媒体类型设置和方法响应设置。下面是我的设置。不确定这些设置是否正确

二进制媒体
在此处输入图像描述

方法响应 在此处输入图像描述

标签: amazon-web-servicesaws-lambdaaws-api-gatewaycontent-type

解决方案


这里是如何解决的

1>添加Binary Media Types。API->设置->二进制媒体类型->添加 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

2>在方法响应中添加Content-DispositionContent-Type标题为状态 200

在此处输入图像描述

3>在集成响应中,将这些标头映射到来自后端的标头。并且还设置了内容处理convert to binary。(我们的后端 api 在正文中返回文件 blob)

在此处输入图像描述


推荐阅读