[英]C# How do i configure AWS API Gateway parameters to map to a basic AWS Lambda Function?
[英]C# AWS Lambda API Gateway from browser - parameters not working
用簡單的 C# AWS Lambda
public string FunctionHandler(string myParam1, ILambdaContext context)
{
return myParam1;
}
我應該如何通過瀏覽器 GET 請求將參數傳遞給 AWS Lambda function + API 網關? 我想要這樣的東西,例如: 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.
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":...
.
好的,我找到了一個解決方案,而不是使用內置的參數解析,而是可以通過讀取 stream 來讀取完整的 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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.