Minimal API in .NET 6 is a great feature. Combined with top-level statements and global using directives you can have a web app that returns “Hello World” with only one source file containing the following few lines:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
Of course this can still be expanded by adding controller support, authorization etc. But in any case we can drastically reduce boiler plate code in our web apps. So of course we also want this in our .NET web apps hosted on AWS Lambda right? Luckily the guys at AWS have our back, but they haven’t really promoted it yet as far as I can see.
The key to making this work in a Lambda is to add the Amazon.Lambda.AspNetCoreServer.Hosting package to your project through NuGet. This allows you to add the following line to the startup logic:
builder.Services.AddAWSLambdaHosting(LambdaEventSource.RestApi);
This will setup your app to process requests coming from an AWS API Gateway REST API. The LambdaEventSource can also be HttpApi and ApplicationLoadBalancer. The final code simply becomes:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAWSLambdaHosting(LambdaEventSource.RestApi);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
That’s it. Have fun changing your Lambda-hosted web apps into using Minimal API!