【问题标题】:C# AWS Lambda API Gateway from browser - parameters not working来自浏览器的 C# AWS Lambda API Gateway - 参数不起作用
【发布时间】:2021-06-29 05:01:23
【问题描述】:

使用简单的 C# AWS Lambda

        public string FunctionHandler(string myParam1, ILambdaContext context)
        {
            return myParam1;
        }

我应该如何通过浏览器 GET 请求将参数传递给 AWS Lambda 函数 + API Gateway? 例如,我想要这样的东西: https://[API ID].execute-api.[REGION].amazonaws.com/myFunc?myParam1=myValue1

在浏览器中显示{"message":"Internal Server Error"}

在日志中显示Error converting the Lambda event JSON payload to a string. JSON strings must be quoted, for example "Hello World" in order to be converted to a string: The JSON value could not be converted to System.String.

不带参数也可以,例如:

        public string FunctionHandler(ILambdaContext context)
        {
            return Utf8Json.JsonSerializer.ToJsonString(context);
        }

在浏览器发送GET请求时https://[API ID].execute-api.[REGION].amazonaws.com/myFunc成功返回{"AwsRequestId":"86ca2da9-438c-4865-8a0b-29d3ced37176","FunctionName":...

【问题讨论】:

  • 在使用 Visual Studio AWS Lambda 函数测试器插件时,以及从 AWS 网站进行测试时,我已经成功地传递了各种参数,但从来没有通过来自浏览器的简单 GET/POST 请求,即我需要什么
  • 您是否尝试在 json 转换逻辑之前打印/记录“ILambdaContext context”的原始内容?看看它何时工作之间的区别[即Visual Studio AWS Lambda 函数测试器插件,以及从 AWS 网站进行测试时] 以及出现问题时 [即来自网络浏览器]
  • 这也可以,但是上下文并不有趣,我只是想看看参数是否在某个地方。我也尝试过使用常量字符串,关键是函数在没有参数的情况下运行。

标签: c# amazon-web-services aws-lambda get aws-api-gateway


【解决方案1】:

好的,我找到了一个解决方案,而不是使用内置的参数解析,而是可以通过读取流来读取完整的 JSON 参数:

public string FunctionHandler(Stream requestStream, ILambdaContext context) { ... }

这里的requestStream里面会有GET/POST的参数或者更大的JSON,但是需要手动解析。请注意,参数可能以 b64 编码(或可能也压缩)发送。一个好方法是找到一个进行这种解析的库。 就我而言,我还编写了消费者 JS 代码,所以我可以确保参数始终以相同的方式出现,这样我的问题就解决了,但如果有人知道这方面的好库,请告诉。

手动 POST 请求数据提取示例,也支持 b64 编码:

        public class StreamBody
        {
            public string body;
            public bool isBase64Encoded;
        }

        public string FunctionHandler(Stream requestStream, ILambdaContext context)
        {
            using var sr = new StreamReader(requestStream);
            var input = sr.ReadToEnd();
            var sbody = Utf8Json.JsonSerializer.Deserialize<StreamBody>(input);
            var body = !sbody.isBase64Encoded ? sbody.body : Encoding.UTF8.GetString(Convert.FromBase64String(sbody.body));

【讨论】:

    猜你喜欢
    • 2019-02-03
    • 2023-03-05
    • 2017-02-27
    • 2016-08-11
    • 2020-01-03
    • 2021-03-31
    • 2020-04-21
    • 2019-01-09
    • 2020-10-10
    相关资源
    最近更新 更多