Wednesday, September 22, 2021

Invoke an AWS Lambda Function in .NET 5

AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. In this article, I will explain how to invoke an AWS Lambda function from within your .NET 5 application.

Prerequisites:
.NET Core / .NET 5 web application with AWSSDK NuGet package installed.

Defining the interface for our service

First, what I like to do is define the interface of what I’m trying to build.
Let’s go for a generic “ILambdaService” that can be reused for invoking different functions as per our need.

My definition would be the following:

public interface ILambdaService
{
    Task<TResponse> InvokeLambdaAsync<TRequest, TResponse>(string functionName, TRequest request);
}

With this, we have an async function called “InvokeLambdaAsync” that defines types for the request and response, and as parameters to our function we need to provide the name of the function that we would like to invoke, and the data that we would like to send in the request.

Implementing our service

First, security.
For invoking the lambda function from your local machine you will need to provide your access, secret key, and region. But when your application is deployed, if it is deployed on AWS, you should not use the access and secret key, instead you should attach a lambda execution role to your application instance.
So for the next part, based on environment, you should consider creating the client with or without “credentials” and “region”. I suggest just using the keys when in your local execution environment.

var credentials = new BasicAWSCredentials("access-key", "secret-key");
var region = RegionEndpoint.GetBySystemName("region");
using var lambdaClient = new AmazonLambdaClient(credentials, region);

Now that we have the “lambdaClient”, next we will need to create the request. In our case that’s our “TRequest”, and we should serialize it to JSON in order to pass it to the lambda function.

var requestJson = JsonConvert.SerializeObject(request);

Next, create the AWSSDK Invoke Request.

var invokeRequest = new InvokeRequest
{
    FunctionName = functionName,
    InvocationType = InvocationType.RequestResponse,
    Payload = requestJson
};

Here we pass in the function name, Payload as our JSON serialized request, and, lastly, InvocationType is the type of invocation we would like to do, and since we are interested in the Response of our lambda function, we are choosing InvocationType.RequestResponse.

If you want to read more on AWS Lambda Invocation types, please refer to this.

Next, using the client and the invoke request we just made, we invoke the function.

var response = await lambdaClient.InvokeAsync(invokeRequest);

Next, some error handling, this can be customized to fit in a logger, or any error handling that you might do.

if (response.HttpStatusCode != HttpStatusCode.OK)
    return default;

Next is to get our response from the Lambda “InvokeResponse” to our “TResponse”. That will be done by decoding the response byte array to a UTF8 JSON string, and then de-serializing it to our desired type “TResponse”. And finally, returning it.

var jsonString = Encoding.UTF8.GetString(response.Payload.ToArray());
var lambdaResponse = JsonConvert.DeserializeObject<TResponse>(jsonString);
return lambdaResponse;

All in all, in my experience invoking an AWS Lambda Function from your .NET 5 application proved very easy.
Some extra stuff worth reading if you considering running this setup is AWS Lambda Cold Starts, AWS Lambda Execution Role, and as I mentioned earlier AWS Lambda Invocation Types.

If you want to read on Polymorphic Binding, refer to my other article.

Danilo Popovikj
A software engineer willing to share.

Related Articles

Invoke an AWS Lambda Function in .NET 5

AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. In this article, I will explain how...

Polymorphic Binding in .NET 5 Web API

In this article, we are going to look at how to implement polymorphic binding in .NET 5 Web API from a JSON request body...

React and .NET Core Web API Authentication using Firebase

Authentication is a key part of any web or mobile application that wants to provide a personalized experience to each of the end-users. It...