首页 文章

如何将AWS API网关中的查询字符串值传递给Lambda C#函数

提问于
浏览
0

我有一个C#方法,我已成功发布为AWS Lambda函数 . 它看起来像这样:

public class MyClass
{
    public async Task<APIGatewayProxyResponse> Test(APIGatewayProxyRequest request, ILambdaContext context)
    {
        return new APIGatewayProxyResponse
        {
            Body = "Body: " + request.Body
                   + Environment.NewLine
                   + "Querystring: " + (request.QueryStringParameters == null ? "null" : string.Join(",", request.QueryStringParameters.Keys)),
            StatusCode = 200
        };
    }
}

我已经完成以下操作来通过Web界面配置我的API网关:

  • 创建了一个新的API

  • 创建了一个名为"myclass"且路径为"/myclass"的新资源

  • 为资源创建了一个新的GET方法,使用"Lambda Function"作为集成类型,并指向我的Lambda函数 .

我希望能够像这样调用我的Lambda函数(不在请求中传递任何指定的头):https://xxx.execute-api.us-east-2.amazonaws.com/prod/myclass?paramA=valueA&paramB=valueB

我不确定如何让我的查询字符串参数传递给lambda函数 . 无论我尝试什么, request.QueryStringParameters 总是为空 .

从这里开始的正确程序是什么?

3 回答

  • 1

    您需要为请求配置url查询字符串参数 .

    • 转到API网关

    • 点击适当的方法,即 GET 方法

    • 转到方法执行

    • 在方法执行中,选择URL查询字符串参数 .

    • 添加查询字符串参数,如paramA,paramB

    • 现在转到“集成请求”选项卡

    • 选择Body Mapping Template,内容类型application / json

    • 生成如下模板

    {
     "paramA":  "$input.params('paramA')",
     "paramB":  "$input.params('paramB')"
    }
    
    • 在lamda函数中接受对中的此键值 .

    希望这会有所帮助 .

  • 1

    好的,我已经找到了问题所在 .

    APIGatewayProxyRequest是从传递给Lambda函数的JSON反序列化的对象 . 如果您接受JObject作为第一个参数,则可以看到传递给Lambda函数的原始JSON:

    public async Task<APIGatewayProxyResponse> Test(JObject request, ILambdaContext context)
    {
        return new APIGatewayProxyResponse
        {
            Body = request.ToString(),
            StatusCode = 200
        };
    }
    

    因此,为了填充APIGatewayProxyRequest,Body Mapping Template中指定的JSON需要匹配APIGatewayProxyRequest的属性 . 这里显示了一个模式示例(尽管它没有显示您需要的实际模板):https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-input-format

    但是,实际上不需要使用APIGatewayProxyRequest . 接受JObject作为Lambda函数的第一个参数更容易,然后您可以访问所需的任何JSON . 然后,您可以使用Vaibs回答中描述的技术 .

  • 0

    请使用“$ input.params('YourQueryStringKey')” .

    您可以在API网关集成响应中创建一个正文映射模板,并尝试“$ input.params('YourQueryStringKey')”或直接在Lambda函数中 .

相关问题