Dot Net For All

Call AWS Lambda Directly using C# code

Hello, my dear friends. In last two article I discussed about the serverless computing, and how we can create serverless code using the lambda in AWS. In this small article I will show how we can call aws lambda function hosted in cloud.

Before going further you can read below articles.

As I  mentioned in previous article, that aws lambda can be called by triggers. But there is a way by which we can directly call the lambda function from C# code.

Call AWS Lambda function using Visual Studio

Create a new visual studio console project. Install the following three nuget packages

as shown in the below figure.

Now coming to the code part. We have to write the following code to call the HelloLambdaWorld function which I have created in previous post.

 static void Main(string[] args)
        {
            AmazonLambdaClient client = new AmazonLambdaClient("awsaccessKeyID", "awsSecreteAccessKey", RegionEndpoint.USWest1);
          

            InvokeRequest ir = new InvokeRequest
            {
                FunctionName = "HelloLambdaWorld",
                InvocationType = InvocationType.RequestResponse,
                Payload = "\"Vikram\""
            };

            InvokeResponse response = client.Invoke(ir);

            var sr = new StreamReader(response.Payload);
            JsonReader reader = new JsonTextReader(sr);

            var serilizer = new JsonSerializer();
            var op = serilizer.Deserialize(reader);

            Console.WriteLine(op);
            Console.ReadLine();
        }

In the above code I have created an instance of the AmazonLambdaClient class which is being used to invoke a request to the “HelloLambdaWorld” function.

The payload is the input which we want to pass to the lambda function. It should be a json string.

If it is some user defined type then we have to convert it into a json string.

Once we execute the code we will get the desired output i.e “Hello Vikram To Lamdab World”.

Conclusion:

In this article and last couple of articles we have understood the basics of serverless computing. How we can utilize the aws lambda to create serverless function and how easy it is to call aws lambda functions from C# code.

 

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview