amazon-web-services - 在 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-type
是application/json
or ,上面的处理程序就可以工作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 代理来实现。
我认为我在这里缺少的是二进制媒体类型设置和方法响应设置。下面是我的设置。不确定这些设置是否正确
解决方案
推荐阅读
- python - 如何使用 MongoEngine 和 Flask-Login 的会话?
- wsdl - 免费 SOAPUI:如何合成/漂亮打印 REST 项目
- rest - 如何使用 REST API 的 powershell 对德语字符(如 ü)进行编码?
- jquery - 如何在执行 ASP.NET 验证后根据用户输入添加确认对话框?
- django - 将 django 与 firestore、非关系数据库一起使用
- python - 如何在 Django 中从 models.py 中查询数据库项?
- python - TypeError unhashable type: 'set' 当你在数据集中提取和选择 nan
- python - 如何通过boto3查找安全组成员的资源
- python - 使用 gcloud python api 获取实例图像名称
- c# - 多次打开/关闭oracle连接c#