How to Write your First AWS Lambda C# Function


The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

AWS Lambda is a compute service that allows you to run code without provisioning or managing servers. This tutorial will guide you through how to write your first function, update it and deploy it with the AWS Command Line Interface (CLI).

The “aws lambda function c# example” is a tutorial on how to write your first AWS Lambda C# Function. The functions are written in the .NET standard and can be run on Windows, Linux, or Mac OSX.

How to Write your First AWS Lambda C# Function

If you’re new to AWS Lambda and want to learn how to use the C# programming language, you’ve come to the correct spot. This post will explain what AWS Lambda is, the advantages of Lambda, and how to create your first AWS Lambda C# Function.

With AWS Lambda C#, you can execute code without having to setup or manage servers. You’ll learn more about what an AWS Lambda is and how to design and enable a basic lambda function using C#, as well as test your new Lambda function in the AWS console.

What is Amazon Web Services Lambda?

AWS Lambda is a serverless solution, which means you don’t have to worry about infrastructure. You may use Lambda to create serverless apps. Furthermore, the fundamental operating system cannot be changed. AWS is in charge of the infrastructure and administration in this situation.

One of the advantages of utilizing AWS Lambda is that you don’t have to worry about:

  • Patching the operating system
  • Threshold scaling
  • Network accessibility
  • Virtual machine management and upkeep

Another significant advantage is that you only pay for what you use. This means you’ll only be paid for the number of requests your code receives and the length of time it takes to execute them. When compared to the monthly cost of hosting a virtual computer in the cloud, this may be a significant savings.


This will be a step-by-step guide. If you want to follow along, make sure you have the following things ready before you start.

What is the purpose of a Lambda function?

A function is used to submit code to execute on AWS Lambda. Before you begin creating your function, you must first determine how it will perform. “Handler” and “Context” are two terms often used to describe Lambda Functions. Lambda gives a context object to the handler when it performs your function.

Each is described as follows in the AWS documentation:

Handler Object — The handler in your Lambda function is the method that handles events. The handler method is called by the runtime when you call a function.

Context Object – Lambda gives a context object to the handler when it performs your function. This object has attributes that include information about the function, invocation, and execution environment.

AWS Lambda C# Function Creation

AWS Lambda for.NET is built on the.NET Core framework, which is open-source and cross-platform. To be clear, C# is a programming language, and.NET is the framework that supports it. Please see the Microsoft documentation for additional information on.NET Core. In AWS Lambda, the most recent supported version of.NET Core is 2.1, which means it doesn’t use the new tools in.NET Core 3.

The.NET core command-line will be used in this presentation. The.NET Core command-line interface (CLI) is a cross-platform toolchain for.NET application development. Please refer to the Microsoft documentation for further details.

Visual Studio may be used to generate Lambda functions as well.

The Lambda Template is installed.

The Amazon.Lambda.Templates NuGet package must be installed first. A NuGet package is a single zip file with the.nupkg extension that includes built code (DLLs), associated files, and a manifest containing package metadata. Type the following into your favourite command-line terminal (PowerShell, CMD, etc. ):

> dotnet new -i Amazon.Lambda.Templates

The Lambda templates will appear as part of the dotnet new command now that you’ve installed them. The dotnet new command generates a new project, configuration file, or solution depending on the template supplied when the command is run.

The following command will demonstrate this by matching the term Lambda:

> dotnet new | Select-String -SimpleMatch ‘lambda’

Searching for Lambda templatesSearching for Lambda templates

For this demonstration, you’ll use Lambda’s EmptyFunction template. A simple Lambda project starts with the EmptyFunction **template. When using the lambda, you may use the following parameters. Dotnet new command using the EmptyFunction template (as seen below):

  • –name – The function’s name.
  • -profile – In your AWS SDK for.NET credentials file, the name of a profile.
  • The AWS Region in which the function will be generated.

An example of a Lambda function created using the default AWS profile is shown below. This is done by issuing the command below, which shows how to create a Lambda function using the default AWS profile:

> dotnet new lambda.EmptyFunction –name MySimpleFunction –profile default –region us-east-1

This command will result in the following success message, as seen in the screenshot:

Creating new Lambda functionsCreating new Lambda functions

You may see the file and directory structure of a path by using the tree command.

The tree output shows that there are two folders, src and test. The src folder contains the primary project code while the test folder contains code for testing.

Examining the contents of the MySimpleFunction folderExamining the contents of the MySimpleFunction folder

The Amazon global tools must then be installed using the dotnet command. In.NET Core, global tools are a new feature. They enable the distribution of command line tools through NuGet packages and installation using the dotnet command line.

Type the following command to install the tools:

> dotnet tool install -g Amazon.Lambda.Tools

When invoking a Lambda function, AWS Lambda C# uses the Function.cs file from the src folder. To keep your code neat, you may create distinct CS files. A source code file created in the C# language is known as a CS file.

The namespace keyword in your CS files uses the same name across each CS file. In larger projects, a namespace is used to assist manage the scope of.NET class and function names.

The Lambda template you ran and built earlier in the post provides a Function.cs template that looks like the screenshot below. Some locations of importance have been identified and numbered:

  1. For.NET Core, the Lambda package. A static Lambda logger, serialization interfaces, and a context object are all included in this module.
  2. The input that comes first is the handler component of the parameter. This might be data from an event or bespoke input.
  3. A serialization library will be required for any Lambda functions that employ input or output types (except for the Stream object). Serialization using Amazon.Lambda. Serialization is accomplished using the Json NuGet package.
  4. You must declare a method parameter of ILambdaContext if you wish to use the Lambda context object information, which includes information such as memory limit and remaining execution time, to mention a few.

Overview of lambda functionsOverview of lambda functions

You will be creating a simple class to take a first name and last name, which will display a welcome message. You will also make use of the context object (described in the “What is the purpose of a Lambda function?” section), and use the Lambda logger (provided in the Amazon.Lambda.Core library), add the function named called.

Writing your first and last names With C#, Create a Welcome Message

Under the.MySimpleFunctionsrc directory Create a new class file, Newuser.cs, for MySimpleFunction. This class will be used to record the first and last names, also known as surnames.

The namespace for the class is MySimpleFunction, and it will include two public strings. The namespace name is the same as in the Function.cs file.

Using System; utilizing System Collections. Generic; System is used. public class NewUser public string firstName get; set; public string surname get; set; text; namespace MySimpleFunction

Open the Function.cs file after saving it.

The name of the main public class will be changed to DisplayNewUser. It will explain how the handler string instructs AWS Lambda C# where to search when executing the function, in addition to making the class more particular.

The function that will run our code will be as follows: When the Lambda function is called, this method is called.

public string FunctionHandler(NewUser input, ILambdaContext context)

Apart from the input type, which now references our Newuser.cs class file, this appears quite similar to the default method supplied in the Function.cs file.

The next two lines make up the method’s primary body:

return $”Welcome: input.firstName & input.surname”; LambdaLogger.Log($”Calling function name: context.FunctionNamen”);

The Log method from the Amazon.Lambda.Core is used to write logs. The LambdaLogger class is part of the Amazon.Lambda.Core Lambda package. The function name is shown using context information. The second line prints the first and last names on the screen.

The following is the whole function.cs file:

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Amazon.Lambda.Core;*// Assembly attribute to enable the Lambda function’s JSON input to be converted into a .NET class.*[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]namespace MySimpleFunction { public class DisplayNewUser {*// <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(NewUser input, ILambdaContext context) { LambdaLogger.Log($”Calling function name: {context.FunctionName}n”); return $”Welcome: {input.firstName} {input.surname}”; } }}

You must first update the aws-lambda-tools-defaults.json file in the source folder before uploading this. The command line arguments for deploying your Lambda function may be found in the aws-lambda-tools-defaults.json input file. The following values are found at the end of the file:

“profile”:”default,” “region”:”us-east-1,” “configuration”:”Release,” “framework”:”netcoreapp2.1,” “function-runtime”:”dotnetcore2.1,” “function-memory-size”:256,” “function-timeout”:30,” “function-memory-size”:256,” “function-memory-size”:256,” “function- “function-handler”:”MySimpleFunction::MySimpleFunction.Function::FunctionHandler”

function-handler* is the line that has to be changed. The line now contains information on how AWS Lambda will call the function MySimpleFunction::MySimpleFunction. Function::FunctionHandler. Remember that in Function.cs, you updated the primary public class to DisplayNewUser. This must be mirrored in the function-handler, which should be changed to DisplayNewUser instead of Function:


You’ll add a new line that says “function-role”: “myBasicExecutionRole.” As the name implies, the function role is the one having the necessary rights to execute the Lambda function. The role of myBasicExecutionRole**,** as defined by AWS, is the least privileged role for executing a Lambda function.

This line is optional, however it will save time when deploying the function if it is included. To deploy the function to AWS, we utilize the dotnet command line once more:

> dotnet lambda deploy-function MySimpleFunction

This command’s output will look somewhat like this:

Creating the function's outputCreating the function’s output

The Lambda Function is being tested.

Navigate to the AWS Services section of the Lambda interface to see the Lambda function you generated. Your function will be mentioned on the main screen:

AWS Management Console's Lambda functionAWS Management Console’s Lambda function

To access the Lambda function, click on the function name. You may use the top of the screen to test our Lambda:

Button for testingButton for testing

Click on the down arrow next to the Button for testing:

Creating test eventsCreating test events

AWS uses the JSON format for input and output. Your event will need to be configured in JSON format.

You just need to give a firstname and surname to setup the event in this demo:

Input in JSON formatInput in JSON format

You’ll need to write the following JSON:

“Graham” as the first name, “Beer” as the surname

Give the Event a name in the corresponding box, mine is simply called MyTestEvent, and click create, at the bottom of the template. You will be returned to the main Lambda page for your function. You can now click on the Button for testing to run your Lambda:

Examining the exam resultsExamining the exam results

The name data you gave to the test event information in JSON format are shown in arrow number 1, with the welcome message coming from the Function.cs file previously.

The second arrow, also from Function.cs, shows the function name you requested.

You may also use the AWS command line to call the Lambda function. Because the JSON is provided through as an argument, you don’t need to setup the test event in this scenario.

Note that under Windows, the double quotes and single quotes must be written at the end for it to work. The code is written as follows:

> aws lambda invoke –region us-east-1 –function-name SimpleFunction –payload ‘”{“”firstName””: “”Graham””, “”surname””: “”Beer””}”‘ output.txt;

You can inspect the contents of the output.txt file generated by the AWS command line you just used using PowerShell’s Get-Content cmdlet:

PS51> Get-Content -Path output.txt

The command line produced a 200 (successful) StatusCode, indicating that you have executed the most recent version of our Lambda function.

The Lambda function output is shown in the output.txt file, as indicated in the picture above with the arrow.

Lambda's PowerShell outputLambda’s PowerShell output


I’ve attempted to cover several aspects of the AWS Lambda procedure in this blog. I love serverless; it’s fantastic to be able to develop without worrying about the underlying infrastructure.

Although the example in this article is quite tiny, it serves as a taster and may inspire you to think of additional methods. . NET Core is a significant player in Lambda, and you have a lot of freedom with it since you can utilize C# and even PowerShell.

AWS Lambda is a service that allows you to run code without provisioning or managing servers. In this tutorial, we will show you how to write your first AWS Lambda function in C#. Reference: aws lambda c# multiple functions.

Related Tags

  • aws lambda function example
  • aws lambda net core 3.1 example
  • create lambda function aws cli
  • aws lambda c# api gateway example
  • how to create a lambda function in python

Table of Content