在AWS API Gateway中重新调整流-> Lambda函数?

时间:2019-01-08 23:55:45

标签: amazon-web-services aws-lambda aws-api-gateway content-type

我已经使用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-typeapplication/jsonapplication/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代理。
我想这里缺少的是二进制媒体类型设置和方法响应设置。以下是我的设置。不确定这些设置是否正确

二进制媒体
enter image description here

方法响应 enter image description here

1 个答案:

答案 0 :(得分:0)

在这里如何解决

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

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

enter image description here

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

enter image description here