joydip_kanjilal
Contributor

How to build AWS Lambda functions in .NET Core

how-to
May 18, 20217 mins
C#Cloud ComputingMicrosoft .NET

Learn how to use .NET Core and the AWS Toolkit for Visual Studio to build serverless functions and deploy them to AWS Lambda in the Amazon cloud.

Java  >  Lambda expressions  >  Lambda symbol / abstract formulas / binary code
Credit: Monsitj / Getty Images

Serverless computing has gained popularity in the last few years primarily because it supports both ease of development and high scalability. Serverless functions are stateless, event-driven, and highly scalable, and they don’t have any dependencies on the underlying infrastructure. AWS Lambda is the leading example of a serverless computing platform.

In this article, we’ll talk about how we can use .NET Core to build and deploy serverless functions on AWS Lambda. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here. In addition, you will need the AWS Toolkit for Visual Studio 2019, which you can download here.

Naturally, you should also have an AWS account since we’ll be building and deploying our serverless functions to AWS Lambda. If you don’t have an AWS account, you can create a free one here.

AWS Lambda project types in Visual Studio

The AWS Toolkit for Visual Studio 2019 includes two .NET Core project templates that can help you build and deploy .NET Core-based AWS Lambda functions quickly. When working with AWS Lambda in Visual Studio, you can choose from either of two project types:

  1. AWS Lambda project: Select the AWS Lambda project type when you want to build and deploy an individual AWS Lambda function. We will leverage the AWS Lambda project type in this article to develop and deploy an AWS Lambda function.
  2. AWS Serverless Application project: Select the AWS Serverless Application project type if you’re developing multiple AWS Lambda functions that you will deploy together as part of an application, using an AWS CloudFormation template to orchestrate the deployment. For example, you could use this project type to create a database, add IAM roles, deploy several functions simultaneously.

Create a new AWS Lambda project in Visual Studio 2019

So let’s create an AWS Lambda project in Visual Studio 2019. Follow these steps to create a new AWS Lambda project leveraging .NET Core in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Click on “Create a new project.”
  3. In the “Create a new project” window, search for and select the AWS Lambda Project (.NET Core – C#) template from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Create.
  8. Select the Empty Function blueprint. (See Figure 1.)
  9. Click Finish.
aws lambda net core 01 IDG

The AWS Toolkit for Visual Studio provides a number of quickstart blueprints for AWS Lambda projects.

A new AWS Lambda project will be created. Note that the project includes a file named Function.cs that contains the following code.

using Amazon.Lambda.Core;
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.
           SystemTextJson.DefaultLambdaJsonSerializer))]
namespace IDGAWSLambda
{
    public class Function
    {
       public string FunctionHandler(string input, ILambdaContext context)
        {
            return input?.ToUpper();
        }
    }
}

We’ll work with this code to create our AWS Lambda function in the subsequent sections of this article.

How does an AWS Lambda function work?

When working with AWS Lambda functions, you will often come across two key components — the function handler and the context object.

The function handler is the entry point to start the execution of your Lambda function. The function handler accepts two parameters — input data as the first parameter and the Lambda context as the second parameter. Note that Lambda functions can be invoked synchronously or asynchronously. If your Lambda functions are long-running, you will want to take advantage of asynchronous invocation.

The context object comprises data pertaining to the invocation, i.e. the method of invocation as well as the execution state. This information is passed to the function handler at the time of execution. For example, you can take advantage of the context to check details on the memory allocation or retrieve the number of milliseconds remaining before the execution of the function times out.

Create a simple Lambda function in Visual Studio 2019

Refer to the Function.cs file containing the Function class that was automatically created with your new AWS Lambda project. Replace the code of the Function.cs file with the following code:

using Amazon.Lambda.Core;
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace IDGAWSLambda
{
    public class Function
    {
        public string FunctionHandler(string input, ILambdaContext context)
        {
            return $"Welcome: {input}";
        }
    }
}

As you can see, our super-simple function takes a string as input and returns the string prefixed by “Welcome: ”.

Deploy the Lambda function to AWS Lambda

You can deploy an AWS Lambda function in two different ways, either by using the AWS Toolkit for Visual Studio or by using the AWS Console. In this example, we’ll use the AWS Toolkit to deploy our Lambda function.

Follow the steps outlined below to deploy the function to AWS Lambda.

  1. Right-click on the project in the Solution Explorer window.
  2. Click “Publish to AWS Lambda…”
  3. In the “Upload to AWS Lambda” screen, you can specify the function name, description, the framework, the Lambda runtime version, assembly name, type name, method name, etc. All of these will be populated automatically, but you can change them if desired. (See Figure 2.)
  4. Click Next.
  5. In the “Advanced Function Details” screen, you can specify the IAM role to allow your Lambda function to access AWS services such as S3.
  6. Click Upload.
aws lambda net core 02 IDG

Figure 2: The details about your Lambda function will be populated automatically but you can change them.

Once the deployment is successful, you’ll be presented with a Function View screen. When you enter a string here and click Invoke, you’ll see the following output:

aws lambda net core 03 IDG

Figure 3: Our simple AWS Lambda function in action.

Retrieve information from the Lambda function’s context object

The following code snippet illustrates how you can write a Lambda function that can return information from the context object such as the request Id, function name, function version, remaining time, and memory limit.

public string FunctionHandler(ILambdaContext context)
{
    string message = $"Request Id: " + context.AwsRequestId + ", ";
    message += "Function Name: " + context.FunctionName + ", ";
    message += "Function Version: " + context.FunctionVersion + ", ";
    message += "Time Remaining: " + context.RemainingTime + ", ";
    message += "Memory Limit (in MB): " +
                context.MemoryLimitInMB.ToString();
    return message;
}

Test your Lambda function from the AWS Management Console

You can now test the Lambda function from the AWS Management Console by following the steps outlined below.

  1. In the AWS Management Console, click on All Services -> Lambda.
  2. From the list of Lambda functions displayed, select the function you’d like to test (the name of the function is “Function” in our example).
  3. In the next screen, select the Test tab.
  4. Click Test to execute the Lambda function.
aws lambda net core 04 IDG

Figure 4: Displaying information from the context object of our simple Lambda function.

The beauty of serverless functions is that they’re easy to create and you need not be concerned about the underlying infrastructure. You can focus on building your functions without worrying about OS-level patching, network connectivity, managing and maintaining virtual machines, or scaling thresholds.

You can use .NET Core and C# to develop serverless functions for AWS Lambda, Microsoft Azure Functions, or Google Cloud Functions. I’ll write more about using .NET Core and C# for serverless computing in my future posts here.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author