如何将查询字符串和标头映射到AWS C#lambda函数参数

时间:2018-12-28 22:27:25

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

我有采用2个查询字符串参数的AWS Gateway REST API

https://xxxxxx.xxxx.us-east-1.amazonaws.com/dev/pets?type=dog&page=1

API的调用者的标头中还包含x-api-key。我希望API网关将querystring参数和x-api-key传递给lambda函数。因此,我在AWS API Gateway Console中将Integration Request配置为如下

enter image description here

lambda函数如下所示

namespace AWSLambda1
{
    public class Function
    {
        public string FunctionHandler(LambdaRequest request, ILambdaContext context)
        {
            return string.Format("{0},{1},{2}", request.Type, request.Page, request.ApiKey);
        }        
    }
}

public class LambdaRequest
{
    public string Type { get; set; }
    public string Page { get; set; }
    public string ApiKey { get; set; }
}

问题
1>当lambda函数接收到请求时,TypePage属性将为NULL。

2>根据文档,API网关可以使用命名约定method.request.header.{param_name}映射http标头,但是当我尝试将地图设置为method.request.header.x-api-key时会引发错误

  

指定了无效的映射表达式:验证结果:警告:   [],错误:[指定了无效的映射表达式参数:   method.request.header.x-api-key]

我不确定如何将这些查询字符串和标头映射到C#lambda对象

(请注意,我已经经历过SO post并建议JObject作为lambda函数的参数。但这仅对我有效,如果我在Use Lambda Proxy integration中启用了Integration Request在这种情况下,API网关会将所有信息传递给lambda。这可能对我有用,但我正努力避免将不需要的信息传递给lambda函数)

1 个答案:

答案 0 :(得分:4)

在此处添加完整答案。

标题问题

首先,您需要确保在Method Request中添加了标头条目,然后才能在Integration Request中将其与映射method.request.header.x-api-key进行映射。发生错误是因为您没有在Method Request部分中添加,而是仅尝试在Integration Request中进行配置。

enter image description here enter image description here

Lambda有效载荷问题

您似乎没有使用Lambda Proxy Integration。如果您使用Lambda代理集成,那么您将获得完整的事件JSON对象事件数据到Lambda。与您分享的post中给出的答案相似。此JSON对象将包含标头,queryparameters,路径变量,url,请求正文等。如果要查看外观示例,只需在Lambda上创建API网关测试事件即可。

现在,如果您不想使用Lambda代理集成,但想限制发送给Lambda的内容,则必须创建集成映射模板以仅向Lambda发送所需的信息,例如标头,有效负载,查询参数等。 。,来自API网关。

示例集成模板。

{
  "body" : $input.json('$'),
  "headers": {
    #foreach($header in $input.params().header.keySet())
    "$header": "$util.escapeJavaScript($input.params().header.get($header))" #if($foreach.hasNext),#end

    #end
  },
  "method": "$context.httpMethod",
  "params": {
    #foreach($param in $input.params().path.keySet())
    "$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end

    #end
  },
  "query": {
    #foreach($queryParam in $input.params().querystring.keySet())
    "$queryParam": "$util.escapeJavaScript($input.params().querystring.get($queryParam))" #if($foreach.hasNext),#end

    #end
  }  
}

参考-

https://kennbrodhagen.net/2015/12/06/how-to-create-a-request-object-for-your-lambda-event-from-api-gateway/

https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html