As of the end of March 2020, AWS Lambda supports ASP.Net Core 3.1. As of mid-March 2020, API Gateway HTTP APIs become generally available. The combination of these two releases means that the best way (in my opinion!) of writing, deploying and running serverless web apps in the cloud is now even better.
My favourite pattern for architecting a serverless .Net website is to put a regular ASP.Net Core website into a Lambda function wholesale. This means that developers can do local development, unit tests, integration tests the exact same way they know and love and take advantage of serverless infrastructure.
This repo contains everything you need to take the standard ASP.Net Core "web API" template and continuously deploy it to AWS Lambda. Here's what's been added:
-
.github/workflows/ci.yml
: This is the GitHub Actions pipeline for building and deploying this project to AWS Lambda. The steps are:- Setting up .Net SDK and AWS Lambda CLI
- Run unit and integration tests
- Run ReSharper checks and reports on PRs
- Build and package app into a zip file suitable for upload to AWS
- Log into AWS (this requires you to configure AWS creds in GitHub)
- Use CloudFormation to deploy the Lambda function and HTTP API
-
src/RoomDataBFF/Program.cs
: This file has been refactored to support the slightly different way that an ASP.Net Core app is started in Lambda. You shouldn't need to touch this file at all, except for changing logging. -
src/RoomDataBFF/Startup.cs
: The only change to this file is to add a (trivial) dependency-injectedIValuesService
to demonstrate integration testing in the test project. -
test/RoomDataBFF.Tests/TestValuesController.cs
: This file demonstrates ASP.Net Core integration tests in the style made possible byMicrosoft.AspNetCore.Mvc.Testing
. A mockIValuesService
is injected. This shows that tests don't have to be written any differently just because the app is hosted in Lambda. -
serverless.yml
: This file contains the entirety of the serverless infrastructure needed to host the website. The key to the file's conciseness is theAWS::Serverless::Function
that can magic up an API.
First, you'll want to create your own copy of this template repo by clicking this button on the top right of this page:
Once your repo has been created, the first run in GitHub Actions will unfortunately fail because you haven't yet setup secrets. You'll want to follow this AWS guide to setup your secrets in GitHub. You'll know it's done correctly when your secrets look like this:
Finally, once your secrets are configured correctly your pipeline will run
successfully. PRs have will run unit tests and building, but only the master
branch will get deployed. To access your website, go to your Action's logs,
click the arrow next to the Deploy step and look for the ApiUrl
output. It
should look something like this:
You can then navigate to that URL in your browser - and add /api/values
onto
the end of the URL to see the fruits of your labour!