C#如何配置AWS API网关参数以映射到基本AWS Lambda函数?

时间:2018-03-17 18:40:30

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

我一般都很擅长使用AWS和云服务,但我正在尝试创建一个处理从DynamodDB中获取项目的后端,如果它们不存在则创建它们。我试图通过使用API​​网关来调用lambda并使用lambda来处理数据库上的工作来实现这一目标。我创建了一种扫描数据库并返回字符串的示例lambda。我是在视觉工作室中使用AWS lambda项目完成的。在视觉工作室和lambda设计器上的测试事件中给它一个字符串的示例输入时,它工作正常并返回包含预期结果的字符串。所以我尝试添加一个新的API作为触发器,我无法弄清楚如何配置它来发送正确的输入。我已经工作了几个小时,我找不到任何有关将数据作为参数发送到lambda的信息。当我尝试在浏览器中运行api时,我得到{" message":"内部服务器错误"}。当我在api网关上测试时,我得到了这个。

Sat Mar 17 18:50:38 UTC 2018 : Endpoint response body before transformations: {
"errorType": "JsonReaderException",
"errorMessage": "Unexpected character encountered while parsing value: {. 
Path '', line 1, position 1.",
"stackTrace": [
"at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)",
"at Newtonsoft.Json.JsonTextReader.ReadAsString()",
"at 
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType
(JsonReader reader, JsonContract contract, Boolean hasConverter)",
"at 
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize
(JsonReader reader, Type objectType, Boolean checkAdditionalContent)",
"at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, 
Type objectType)",
"at Newtonsoft.Json.JsonSerializer.Deserialize[T](JsonReader reader)",
"at Amazon.Lambda.Serialization.Json.JsonSerializer.Deserialize[T](Stream 
requestStream)",
"at lambda_method(Closure , Stream , Stream , LambdaContextInternal )"
]
}

Sat Mar 17 18:50:38 UTC 2018 : Endpoint response headers: {X-Amz-Executed- 
Version=$LATEST, x-amzn-Remapped-Content-Length=0, Connection=keep-alive, x- 
amzn-RequestId=15d89cfe-2a14-11e8-982c-db6e675f8b1d, Content-Length=939, X- 
Amz-Function-Error=Unhandled, Date=Sat, 17 Mar 2018 18:50:38 GMT, X-Amzn- 
Trace-Id=root=1-5aad637e-629010f757ae9b77679f6f40;sampled=0, Content- 
Type=application/json}
Sat Mar 17 18:50:38 UTC 2018 : Execution failed due to configuration error: 
Malformed Lambda proxy response
Sat Mar 17 18:50:38 UTC 2018 : Method completed with status: 502

下面是我的lambda的副本,我通过将其添加为触发器并将其设置为打开安全性来配置API。我只是不明白如何将参数设置为目标输入。

TESTLAMBDA

[assembly:LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace FindItem
{
public class Function
{

    /// <summary>
    /// A simple function that takes a string and does a ToUpper
    /// </summary>
    /// <param name="input"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public string FunctionHandler(string input, ILambdaContext context)
    {

        AmazonDynamoDBClient client = GetClient();

        Table table = GetTableObject(client, "Stores");
        if (table == null)
        {
            PauseForDebugWindow();
            return "Failure";
        }

        ScanFilter filter = new ScanFilter();
        filter.AddCondition("Item_name", ScanOperator.Contains, new DynamoDBEntry[] { input });
        ScanOperationConfig config = new ScanOperationConfig
        {
            AttributesToGet = new List<string> { "Store, Item_name, Aisle, Price" },
            Filter = filter
        };

        Search search = table.Scan(filter);
        List<Document> docList = new List<Document>();

        Task<String> obj = traversedoc(docList,search);

        return obj.Result;
    }


    /// /////////////////////////////////////////////////////////////////////////

    public async Task<String> traversedoc(List<Document>docList,Search search)
    {

        string astring = "";

        do
        {
            try
            {
                docList = await search.GetNextSetAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n Error: Search.GetNextStep failed because: " + ex.Message);
                break;
            }
            foreach (var doc in docList)
            {

                 astring = astring + doc["Store"] + doc["Item_name"] + doc["Aisle"] + doc["Price"];

            }
        } while (!search.IsDone);

        return astring;

    }

    public static AmazonDynamoDBClient GetClient()
    {
        // First, set up a DynamoDB client for DynamoDB Local
        AmazonDynamoDBConfig ddbConfig = new AmazonDynamoDBConfig();
        AmazonDynamoDBClient client;
        try
        {
            client = new AmazonDynamoDBClient(ddbConfig);
        }
        catch (Exception ex)
        {
            Console.WriteLine("\n Error: failed to create a DynamoDB client; " + ex.Message);
            return (null);
        }
        return (client);



    }


    public static Table GetTableObject(AmazonDynamoDBClient client, string tableName)
    {
        Table table = null;
        try
        {
            table = Table.LoadTable(client, tableName);
        }
        catch (Exception ex)
        {
            Console.WriteLine("\n Error: failed to load the 'Movies' table; " + ex.Message);
            return (null);
        }
        return (table);
    }

    public static void PauseForDebugWindow()
    {
        // Keep the console open if in Debug mode...
        Console.Write("\n\n ...Press any key to continue");
        Console.ReadKey();
        Console.WriteLine();
    }


}
}

1 个答案:

答案 0 :(得分:0)

事实证明,Lambda代理集成已经过检查。这是我在集成请求中的资源方法。我特别确定这是做了什么但是一旦我取消选中我只能使用post方法发送请求正文。所以现在当我在请求体中只发送文本(&#34; milk&#34;)时,它作为我的输入字符串参数接收并正常运行!