invoke a lambda function using aws sdk in csharp

You can use the AWS SDK for .NET to invoke an AWS Lambda function from a C# application using the InvokeAsync method of the AmazonLambdaClient class. Here's an example code snippet:

main.cs
using System;
using System.IO;
using System.Threading.Tasks;
using Amazon.Lambda;
using Amazon.Lambda.Model;

namespace LambdaInvokeExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string functionName = "my-function-name";
            string payload = "{\"key1\": \"value1\", \"key2\": \"value2\", \"key3\": \"value3\"}";

            var client = new AmazonLambdaClient();

            var request = new InvokeRequest
            {
                FunctionName = functionName,
                Payload = payload
            };

            try
            {
                var response = await client.InvokeAsync(request);

                if (response.StatusCode == 200)
                {
                    using (var reader = new StreamReader(response.Payload))
                    {
                        var result = await reader.ReadToEndAsync();
                        Console.WriteLine("Function response: \n" + result);
                    }
                }
                else
                {
                    Console.WriteLine("Error: " + response.StatusCode);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }

            Console.ReadLine();
        }
    }
}
1341 chars
50 lines

In this example, the functionName variable should be replaced with the name of your Lambda function as it appears in the AWS console. The payload variable should contain any input data to be passed to the Lambda function as a JSON string.

The InvokeRequest object is used to configure the invocation request, including the function name and payload. The InvokeAsync method is used to actually send the request and receive the response.

The response from the Lambda function is retrieved as a stream, which can then be read and processed as needed. In this example, the response is simply written to the console.

Note that you will need to have valid AWS credentials configured in your application, either through environment variables or an AWS profile, in order to invoke the Lambda function.

gistlibby LogSnag