Blog Logo

Hosting a .NET 6 Minimal API in AWS Lambda

The .NET 6 runtime for AWS Lambda is here! With it comes many new features such as an improved ILambdaLogger, support for C# 10, top-level statements and many more. But one new cool feature, originally added in .NET 5, is the ability to create minimal APIs. AWS doesn’t provide a managed runtime for .NET 5 so this is the first time you can use this feature in Lambda without using a custom runtime or container image. We’ll use AWS API Gateway HTTP API to trigger the Lambda. This solution is great for an API that isn’t hit very often, or has spikes in request every so often. When there are no requests, it doesn’t cost anything. However this would not be ideal for an API that is very latency sensitive, as cold starts will add 200ms+, depending on your memory configuration. Additionally, this solution would not be suited for a very large application because there is a limit on the deployment package size. Before continuing, be sure you have the .NET 6 SDK installed. Creating the API project Initialize the project, and then add the Amazon.Lambda.AspNetCoreServer.Hosting package. This package is what allows us to process incoming Lambda events as HTTP requests. dotnet new webapi --name LambdaAPI cd LambdaAPI dotnet add package Amazon.Lambda.AspNetCoreServer.Hosting Inside Program.cs, add this line where the services are being defined: builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi); When running in Lambda, this method will swap Kestrel with Amazon.Lambda.AspNetCoreServer which converts the request from API Gateway into the class ASP.NET Core expects and likewise converts the response in the opposite direction. When running locally this method will do nothing, and you will be able to run/debug just like a normal ASP.NET Core API. This method supports 3 lambda event sources; HttpApi, RestApi, and ApplicationLoadBalancer. We’ll be using HttpApi for this guide. Now, we’ll set up a couple routes using the new minimal API syntax. Add these two lines: app.MapGet(/, () => Hello, world!); app.MapGet(/route, () => Hello from /route!); Your Program.cs file should look similar to this: var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment())