In this tutorial, you will create an AWS Lambda that exposes an ASP.NET service. The tutorial will follow these steps:
- Install and configure required tools
- Create a New AWS Lambda .NET project
- Code the Lambda Function in C#
- Upload the Lambda Function to AWS
- Invoke the Function using AWS CLI
- Test the Function in the AWS Console
Part 1 – Install and configure required tools
In this part, you will check for the existence of the following tools and install them if needed. Tools that need to be set up will be configured as well.
- AWS CLI
- .NET Core CLI
- .NET Amazon.Lambda.Tools
- Amazon.Lambda.Templates
AWS CLI – Amazon AWS Command Line Interface
The AWS CLI allows you to send commands directly to AWS services. We’ll use it later to check on the uploaded lambda function.
1. Open a cmd prompt on your development machine and execute the following command:
aws --version
If the AWS CLI is installed you should see something like this:
aws-cli/2.4.21 Python/3.8.8 Windows/10 exe/AMD64 prompt/off
Notice the version number. It should be 2.0.0 or later.
If the AWS CLI is NOT installed you will see this:
'aws' is not recognized as an internal or external command, operable program or batch file.
2. If AWS CLI is not installed, or the installed version is < 2.0.0 then follow the instructions here for installing or upgrading the AWS CLI:
https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html
3. Once the AWS CLI is installed you will need to configure it with a set of Valid AWS credentials.
4. Run the following command to see if credentials have already been set up:
aws s3 ls
If credentials have been configured you will get an empty output or one that includes a listing of available S3 buckets.
If credentials have NOT been configured, you will see this:
Unable to locate credentials. You can configure credentials by running "aws configure".
5. If credentials have not been configured execute the following command to do so. You will need a key file containing your AWS credentials to complete this step. (if you do not have a key file follow the instructions below for obtaining one)
aws configure
The command will prompt you for the following values:
AWS Access Key ID: {take value from the key file} AWS Secret Access Key: {take value from the key file} Default region name: us-west-2 Default output format: json
Obtaining A Key File
Only follow these instructions if you don’t already have a key file.
- Log into AWS console with your user credentials
- Open the IAM console
- Choose ‘Users’
- Choose your own user name from the list
- Select the tab labeled ‘Security credentials’
- Click on [Create access key] (if there are already two access keys you will need to delete one in order to create a new one)
- Once the key has been created choose the option to DOWNLOAD the key pair. Once you leave the screen you will no longer have the chance to download the key pair file.
- Once you’ve downloaded the file you may try choosing SHOW to see the Access Key ID and the Secred access key. The values you see here are the same as the ones you will find in the downloaded key file.
6. Once you have configured the AWS credentials try the following command again:
aws s3 ls
You should no longer get the warning “Unable to locate credentials”.
.NET Core Command Line Interface (CLI)
The .NET CLI is included in the .NET SDK. The .NET SDK is installed as part of Visual Studio and can also be installed separately. In this section you will check to see if the .NET CLI is already installed and to install it if needed.
1. Open a command prompt and execute the following command to see if .NET CLI is installed:
dotnet --version
If the CLI is installed you should get a version number like this:
6.0.200
If the CLI is not installed you will get:
'dotnet' is not recognized as an internal or external command, operable program or batch file.
2. If the CLI is not installed, follow these instructions to install it.
- Download .NET 6.0 from the following page: https://dotnet.microsoft.com/en-us/download/dotnet
You will get a file like this one:
dotnet-sdk-6.0.200-win-x64.exe
- Execute the file and follow prompts to install the SDK
- After the installation is completed, open a command prompt and execute this command to check, if all is good the version number will be returned.
dotnet --version
.NET Amazon.Lambda.Tools
1. Open a command prompt.
2. Try invoking the lambda tools with this command:
dotnet lambda
If you see this message then the tools are installed and you can skip to the next section.
Amazon Lambda Tools for .NET Core applications (5.3.0)
If the amazon.lambda.tools are not installed you will see the following warning message:
Could not execute because the specified command or file was not found.
3. Execute the following command to install the Amazon.Lambda.Tools :
dotnet tool install --global Amazon.Lambda.Tools
You should see the output:
You can invoke the tool using the following command: dotnet-lambda Tool 'amazon.lambda.tools' (version '5.3.0') was successfully installed.
4. Go back to step __2. above and verify that you can access the tools.
Amazon Lambda Templates
.NET CLI creates new projects based on templates. To create projects that can produce functions for the AWS Lambda service we need to install the related templates.
1. Check to see if amazon lambda templates are installed by executing the following command:
dotnet new --list
This should produce a list of templates.
2. Scroll down through the list and look for the following template:
Lambda Empty Function lambda.EmptyFunction [C#],F# AWS/Lambda/Function
This is the template we’ll be using. If it is NOT in the list then continue with the next few steps to load the Amazon Lambda Templates.
3. Execute the following command at the command prompt to install the Amazon Lambda Templates:
dotnet new --install Amazon.Lambda.Templates
You should see a list of templates that were just installed.
4. Go back to step __1. above and verify that the lambda templates are installed.
Part 2 – Create a New AWS Lambda .NET project
In this part you will create a new empty .NET project that is suitable for creating a lambda function that can be uploaded to AWS.
1. Open a command prompt.
2. Create the directory C:\LabWorkDotNet:
mkdir C:\LabWorkDotNet
3. Navigate into the directory you just created:
cd C:\LabWorkDotNet
4. Execute the following command to create a new project BasicLambda:
dotnet new lambda.EmptyFunction --name BasicLambda
This will create the subdirectory “BasicLambda” and you will see the message:
The template "Lambda Empty Function" was created successfully.
5. Navigate into the created project directory:
cd BasicLambda
6. Use the directory command to verify that the BasicLambda directory contains the two directories: src, and test.
dir
7. Navigate to the following directory:
cd C:\LabWorkDotNet\BasicLambda\src\BasicLambda
8. Use the directory command to verify the contents of the directory. You should see the following four files:
02/22/2022 09:50 AM 718 aws-lambda-tools-defaults.json 02/22/2022 09:50 AM 675 BasicLambda.csproj 02/22/2022 09:50 AM 771 Function.cs 02/22/2022 09:50 AM 2,182 Readme.md
The Function.cs file is where we will be coding our lambda function.
Part 3 – Code the Lambda Function in C#
In this section, you will code the lambda function.
1. Open the following file in an editor:
C:\LabWorkDotNet\BasicLambda\src\BasicLambda\Function.cs
2. Scrolling down, you should see the following code:
namespace BasicLambda
public class Function
{
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(string input, ILambdaContext context)
{
return input?.ToUpper();
}
}
3. Add the following class inside the namespace, above ‘public class Function’:
public class Person {
public string firstName { get; set; }
public string lastname { get; set; }
}
4. Make the following change:
Change: public class Function To: public class Greeter
5. Make the following change:
Change: public string FunctionHandler(string input, ILambdaContext ...) To: public string GreetPerson(Personperson, ILambdaContext context)
6. Replace the contents of the GreetPerson method with the following:
LambdaLogger.Log($"Calling: {context.FunctionName}\n"); return $"Welcome: {person.firstName} {person.lastname}";
7. Check your code, it should match the following:
namespace BasicLambda
public class Person {
public string firstName { get; set; }
public string lastname { get; set; }
}
public class Greeter
{
/// <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 GreetPerson(Person person, ILambdaContext context)
{
LambdaLogger.Log($"Calling: {context.FunctionName}\n");
return $"Welcome: {person.firstName} {person.lastname}";
}
}
The function above has the following handle syntax:
{Project}::{Namespace}.{{Class}}::{Function} BasicLambda::BasicLambda.Greeter::GreetPerson
8. Save and close the Function.cs file.
9. Open the following file in an editor:
C:\LabWorkDotNet\BasicLambda\src\BasicLambda\aws-lambda-tools-defaults.json
10. Find and change the following line as shown below:
From This:
"function-handler": "BasicLambda::BasicLambda.Function::FunctionHandler"
To This:
"function-handler": "BasicLambda::BasicLambda.Greeter::GreetPerson"
11. Find and change the following two lines as shown below:
From This:
"profile": "", "region": "",
To This:
"profile": "default", "region": "us-west-2",
12. Save and close the aws-lambda-tools-defaults.json file.
Part 4 – Upload the Lambda Function to AWS
In this part, you will upload the function created in the previous part to the AWS Lambda service.
Before we upload the function let’s check for any existing functions in the AWS Lambda service.
1. Execute the following from the command prompt:
aws lambda list-functions
You should see the following output, indicating that there are no functions:
{ "Functions": [] }
2. Navigate to the following directory:
cd C:\LabWorkDotNet\BasicLambda\src\BasicLambda
3. Execute the following command to load the function to AWS:
dotnet lambda deploy-function BasicLambda
The command may stop at the following prompt:
Select IAM Role that to provide AWS credentials to your code: 1) ExampleFunction-role-yi188kko 2) myBasicExecutionRole 3) MySimpleFunction2-role-omxsu9z5 4) *** Create new IAM Role ***
If so then choose “Create new IAM Role” by entering the number next to it, and hit {enter}.
You will be prompted:
Enter name of the new IAM Role:
4. Enter the following and hit the {enter} key:
myBasicLambdaExecutionRole
You will be prompted:
Select IAM Policy to attach to the new role and grant permissions:
5. Enter the number next to “AWSLambdaExecute” and hit {enter}:
The Role will be created and propagated to various AWS regions. When that’s done you will see the message:
New Lambda function created
6. Execute the following from the command prompt to verify that the function was added to AWS:
aws lambda list-functions
You should see the following output, indicating that the function has been added to AWS:
{ "Functions": [ { "FunctionName": "BasicLambda", ... } ] }
Part 5 – Invoke the Function using AWS CLI
In this section, you will invoke the Lambda function that was just uploaded to AWS.
1. Open a command prompt.
2. Execute the following command:
aws lambda invoke --function-name BasicLambda output.txt
You should get the output:
{ "StatusCode": 200, "ExecutedVersion": "$LATEST" }
3. Check the output.txt file using this command:
more < output.txt
You should get the output:
"Welcome: "
4. The above output is correct. We didn’t pass any data for the ‘person’ parameter so no person was included in the return value.
5. The command to invoke the function with parameters is a bit more involved. Try running it from the command prompt [enter the command in 1 line]:
aws lambda invoke --function-name BasicLambda --cli-binary-format raw-in-base64-out --payload "{\"firstName\": \"John\", \"lastname\": \"Doe\"}" output.txt
If you have any problems try copying the command to a text editor and removing any carriage returns so that its all on the same line. Then cut and paste into the cmd prompt.
You should see the output:
{ "StatusCode": 200, "ExecutedVersion": "$LATEST" }
6. Check the output.txt file using this command:
more < output.txt
You should get the output:
"Welcome: John Doe"
This greeting output shows the person we passed on the command line.
Part 6 – Test the Function in the AWS Console
In this part, you will try running the function from the AWS Lambda service console.
1. Open a browser to the following URL:
https://aws.amazon.com/console/
2. Sign in with your AWS credentials.
3. After signing in, navigate to the Lambda console by entering the text “lambda” in the search bar at the top of the screen and hitting enter.
4. Once in the Lambda console, click on ‘Functions‘ in the area to the left of the screen:
Now you should see “BasicLambda” in the list of functions.
If you do not see BasicLambda in the list check the region setting in the upper right of the page. It should say “Oregon” which corresponds to the us-west-2 region. This setting needs to match with the default region for the credentials used to upload the function to AWS.
If the current region in the Lambda console does not match then click on the dropdown and select the matching region. BasicLambda should now appear in the list.
5. Click on ‘BasicLambda‘ to open up its edit screen.
6. Click on the ‘Test‘ tab at the bottom of the page. Then scroll down until you see the testing interface.
7. Update the data in the editor at the bottom of the page to match the following:
{
"firstname": "Sarah",
"lastname": "Conner"
}
8. Enter the text “person” in the “Name” field and click on the [Save Changes] button.
9. Click on the [Test] button to run the test.
You should see the following on-screen when the test is done:
10. Click on ‘details’ to review the results.
The text returned is shown and should be “Welcome: Sarah Conner”.
If the results indicate failure, click on ‘details‘ and/or (logs) to determine the cause of the failure.
Part 7 – Review
In this tutorial you:
- Setup required software,
- Created an AWS .NET project,
- Coded a Lambda function in C#,
- Uploaded the function to the AWS Lambda service,
- Tested the function from the command line using ‘aws lambda invoke”
- Tested the function from the AWS Lambda Console