Start a new project
To demonstrate how to run an ASP.NET minimal API on AWS Lambda let's start with a brand new project. It's possible to do this by adding a single line of code to your application.
To create a new minimal API run the below command:
Once initialised, open the project in the IDE of your choice. The sample API contains a single endpoint with a /weatherforecast
endpoint.
Adding Lambda support
AWS provides a Nuget package that makes it simple to run ASP.NET on Lambda. In fact, for minimal API's you can do that by adding a single line of code to the application. To start, let's add the Nuget package. Navigate to the folder containing the created .csproj
file and run:
Once installed, all you need to do is add a single line of code to the Program.cs
file. That line is:
The call to AddAWSLambdaHosting takes a single parameter. This parameter will differ based on which if the API options is sourcing your Lambda function. The options are API Gateway HTTP or REST API's, as well as an Application Load Balancer.
One of the interesting things about the AWS tooling is that it understands the context in which the API is running. If you run the application on your local machine the built in Kestrel web server will be used. Once running in Lambda, an in memory web server is used.
Under the hood, the tooling takes the event payload Lambda receives and converts that to a HTTP request that ASP.NET understands. The ASP.NET response is then translated back to the response format Lambda expects.
Ensure that line is added before the call to builder.Build();
.
And that's it, that is all you need to do to enable your minimal API to be hosted on AWS Lambda. To deploy this to AWS Lambda, you can follow the instructions in the deploy tutorial.