我已经使用https://api.mydomain.com/v1/download?id=1234"
之类的AWS api网关创建了一个API。 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
或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\"");
当我从浏览器访问“网址”并尝试打开文件时。我收到错误消息
Excel cannot open the file
Report.xlsx becuase 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网关现在支持的AWS doc二进制数据。现在按照文档
您可以指定是否希望API网关通过 通过整合请求和响应正文,将它们转换为文本 (Base64编码),或将其转换为二进制文件(Base64解码)。这些 选项可用于HTTP,AWS Service和HTTP Proxy 整合。对于Lambda函数和Lambda函数代理 集成(目前仅支持JSON),请求主体为 始终转换为JSON。
我正在使用Lambda函数代理,该代理当前支持JSON。但是example here展示了如何使用Lambda代理。
我想这里缺少的是二进制媒体类型设置和方法响应设置。以下是我的设置。不确定这些设置是否正确