Running .NET on AWS Lambda: A Complete Beginner’s Guide


Introduction to AWS Lambda and .NET

AWS Lambda is a serverless computing service that runs code in response to events and automatically manages the underlying infrastructure. With support for .NET Core and .NET 6+, Lambda allows C# developers to run backend logic without provisioning or managing servers.

AWS Lambda supports:

  • .NET 6 (LTS)

  • .NET 8 (as a container image)

  • Older versions like .NET Core 3.1 are deprecated as of Dec 2023

Prerequisites

Before deploying your .NET app to Lambda, ensure you have:

.NET SDK (6 or 8)

AWS CLI installed and configured

AWS Toolkit for Visual Studio (optional for IDE integration)

Amazon.Lambda.Tools global tool:


dotnet tool install -g Amazon.Lambda.Tools


Project Setup

1. Create a New Lambda-Compatible Project

You can use AWS-provided templates:


dotnet new lambda.EmptyFunction --name MyLambdaApp

cd MyLambdaApp


This creates a minimal function using:

  • Function.cs: contains the handler

  • aws-lambda-tools-defaults.json: configures deployment details

2. Sample Function Code


public class Function

{

    public string FunctionHandler(string input, ILambdaContext context)

    {

        return $"Hello from Lambda, input was: {input}";

    }

}


Packaging and Deployment

Option 1: Deploy Using Amazon.Lambda.Tools


dotnet lambda deploy-function MyLambdaApp


This command:

  • Packages your code

  • Uploads it to AWS

  • Creates or updates the Lambda function

Option 2: Deploy as a Container (for .NET 8 or custom dependencies)

Create a Dockerfile:


FROM public.ecr.aws/lambda/dotnet:8 AS base

WORKDIR /var/task

COPY . .

CMD ["MyLambdaApp::MyLambdaApp.Function::FunctionHandler"]


Build and push your Docker image to Amazon ECR, then deploy from the Lambda console or CLI.

Event Triggers

You can connect your Lambda to various AWS services:

  • API Gateway (for HTTP triggers)

  • S3 (for object events)

  • DynamoDB Streams

  • CloudWatch Events

Example: Trigger from API Gateway


{

  "httpMethod": "GET",

  "path": "/hello",

  "headers": { ... }

}


Local Testing

You can run your function locally using:


dotnet lambda invoke-function MyLambdaApp --payload "Test input"


Or use AWS Lambda Test Tool (GUI-based testing tool for .NET):


dotnet tool install -g Amazon.Lambda.TestTool-6.0

dotnet lambda test-tool


Monitoring and Logs

Logs are automatically sent to Amazon CloudWatch. You can:

  • View logs in AWS Console under CloudWatch > Logs

  • Set up CloudWatch Alarms

  • Use AWS X-Ray for distributed tracing

Best Practices

  • Use async/await for non-blocking operations

  • Keep the package size small to reduce cold start times

  • Handle exceptions gracefully and log context for debugging

  • Use environment variables for configuration

  • Consider using Amazon Lambda Powertools for .NET for observability

Comments

YouTube Channel

Follow us on X