• Home
  • Creating a serverless .NET Core 2.1 Web Api with AWS Lambda

Creating a serverless .NET Core 2.1 Web Api with AWS Lambda

Before start you need 2-3 things installed and configured. These are Visual Studio 2017 (on your machine), AWS Toolkit for Visual Studio (if you work on windows machine) and AWS account . If you have Mac like I do you can’t take advantages of AWS Toolkit for Visual Studio but instead you must do some things from CLI. In article below I will show you example with CLI ( create, deploy and publish .NET Core to AWS)

AWS Lambda is the serverless product offered by Amazon Web Services. Serverless does not mean that there is no server involved – obviously there is – but just that managing servers, scaling, etc is not something that you need to worry about.

What you need to worry about (as programmer) is writing the code that executes the logic. You can then deploy it to a serverless environment such as AWS Lambda and it will take care of scaling etc. Some of the other offerings available are Azure FunctionsGoogle Cloud Functions and also Webtask.

The other advantage is that serverless environments only charge you for the time your code takes to execute. So if you have a small POC you want to develop, this is ideal as you do not have to worry about paying for a server which sits idle 99% of the time.

First you need to add Amazon Templates to your dotnet CLI

dotnet new -i Amazon.Lambda.Templates::*

The trailing ::* in the command specifies to install the latest version. Once the install is complete, the Lambda templates show up as part of dotnet new.

Template Instantiation Commands for .NET Core CLI.                                                                            
                                                                                                                             
Templates                            Short Name                    Language      Tags                                         
------------------------------------------------------------------------------------------------------                                                      
Lambda Detect Image Labels           lambda.DetectImageLabels      [C#]          AWS/Lambda/Function                          
Lambda Empty Function                lambda.EmptyFunction          [C#]          AWS/Lambda/Function                          
Lambda Simple DynamoDB Function      lambda.DynamoDB               [C#]          AWS/Lambda/Function                          
Lambda Simple Kinesis Function       lambda.Kinesis                [C#]          AWS/Lambda/Function                          
Lambda Simple S3 Function            lambda.S3                     [C#]          AWS/Lambda/Function                          
Lambda ASP.NET Core Web API          lambda.AspNetCoreWebAPI       [C#]          AWS/Lambda/Serverless                        
Lambda DynamoDB Blog API             lambda.DynamoDBBlogAPI        [C#]          AWS/Lambda/Serverless                        
Lambda Empty Serverless              lambda.EmptyServerless        [C#]          AWS/Lambda/Serverless                        
Console Application                  console                       [C#], F#      Common/Console                               
Class library                        classlib                      [C#], F#      Common/Library                               
Unit Test Project                    mstest                        [C#], F#      Test/MSTest                                  
xUnit Test Project                   xunit                         [C#], F#      Test/xUnit                                   
ASP.NET Core Empty                   web                           [C#]          Web/Empty                                    
ASP.NET Core Web App                 mvc                           [C#], F#      Web/MVC                                      
ASP.NET Core Web API                 webapi                        [C#]          Web/WebAPI                                   
Nuget Config                         nugetconfig                                 Config                                       
Web Config                           webconfig                                   Config                                       
Solution File                        sln                                         Solution                                     
                                                                                                                             
Examples:                                                                                                                     
    dotnet new mvc --auth None --framework netcoreapp1.1                                                                      
    dotnet new classlib                                                                                                       
    dotnet new --help

So, after that we can create working directory on our local machine and cd into it

mkdir chrisexamples
cd chrisexamples

In next step we run

dotnet new serverless.AspNetCoreWebApi

As you see I choose Lambda ASP.NET Core Web API because I want to create simple Web Api example as AWS/Lambda/Serverless Application

When you ls your created directory (chrisexamples) you can see that inside are two directories “src” and “test”. We will be using project (solution) in our src folder.

cd src/chrisexamples
dotnet restore

My sample Web Application is created and I can test it in Postman. If I request URL (GET method) ex. localhost:5000/api/values which represents route for our ValuesController in our sample we get JSON response

[
    "value1",
    "value2"
]

When you examine your project folder you will see basic .NET Web Api infrastructure so you can create any type of application that you like. But let’s see some important files inside. First you will see LambdaEntryPoint.cs. This file is used as main entry point when app is used in AWS. File LocalEntryPoint.cs is file that is used for local test and debug app. Most important file is serverlessTemplate. The lambda entry point is configured inside serverless template as a handler for all traffic coming through API gateway. Also you can see the {proxy+} in Resources->Events->Paths. This function is configured as a proxy resource and all traffic that coming in that path will be sent to to handler function as async (  chrisexamples::chrisexamples.LambdaEntryPoint::FunctionHandlerAsync ).  In that file you can see also S3 bucket resources and settings. If you want to know more how this processes are handled go to official AWS documentation ( *I have basic understanding of that and I’m not expert in that fields so don’t ask me 🙂 ).

Now we can deploy and publish our .NET Core Web Api application to AWS. To do this go to your AWS and create new IAM User and give him proper permissions (policies) for AWS Lambda and AWS CloudFormation, and also new S3 bucket in your chosen region. How to create this is not covered in this article because it’s out of scope of this article but you can go to AWS and get all informations that you need about these services.

After you create user copy user aws-access-key-id and aws-secret-key to your computer because you will need them in the next step

Run

dotnet lambda deploy-serverless --region < here you put your region ex. eu-central-1 >
                                --aws-access-key-id < put your user access key id >
                                --aws-secret-key < put your user aws-secret-key >

When you run code above you will be promt for some infos:

– stack name : In my example I just put chrisexamples

– S3 bucket name: In my example S3 bucket that I created in AWS was named chrisexamples

– CloudFormation Stack Name: I put chrisexamples….

After few minutes everything is created for you and you can test your published .NET Core App

Timestamp            Logical Resource Id                      Status                                   
-------------------- ---------------------------------------- ---------------------------------------- 
10/29/2018 14:05     chrisexamples                            CREATE_IN_PROGRESS                      
10/29/2018 14:05     AspNetCoreFunctionRole                   CREATE_IN_PROGRESS                      
10/29/2018 14:05     Bucket                                   CREATE_IN_PROGRESS                      
10/29/2018 14:05     AspNetCoreFunctionRole                   CREATE_IN_PROGRESS                      
10/29/2018 14:05     Bucket                                   CREATE_IN_PROGRESS                      
10/29/2018 14:06     Bucket                                   CREATE_COMPLETE                         
10/29/2018 14:06     AspNetCoreFunctionRole                   CREATE_COMPLETE                         
10/29/2018 14:06     AspNetCoreFunction                       CREATE_IN_PROGRESS                      
10/29/2018 14:06     AspNetCoreFunction                       CREATE_IN_PROGRESS                      
10/29/2018 14:06     AspNetCoreFunction                       CREATE_COMPLETE                         
10/29/2018 14:06     ServerlessRestApi                        CREATE_IN_PROGRESS                      
10/29/2018 14:06     ServerlessRestApi                        CREATE_IN_PROGRESS                      
10/29/2018 14:06     ServerlessRestApi                        CREATE_COMPLETE                         
10/29/2018 14:06     AspNetCoreFunctionPutResourcePermissionTest CREATE_IN_PROGRESS                      
10/29/2018 14:06     ServerlessRestApiDeployment***********   CREATE_IN_PROGRESS                      
10/29/2018 14:06     AspNetCoreFunctionPutResourcePermissionTest CREATE_IN_PROGRESS                      
10/29/2018 14:06     AspNetCoreFunctionPutResourcePermissionProd CREATE_IN_PROGRESS                      
10/29/2018 14:06     ServerlessRestApiDeployment***********    CREATE_IN_PROGRESS                      
10/29/2018 14:06     AspNetCoreFunctionPutResourcePermissionProd CREATE_IN_PROGRESS                      
10/29/2018 14:06     ServerlessRestApiDeploymentf**********    CREATE_COMPLETE                         
10/29/2018 14:06     ServerlessRestApiProdStage               CREATE_IN_PROGRESS                      
10/29/2018 14:06     ServerlessRestApiProdStage               CREATE_IN_PROGRESS                      
10/29/2018 14:06     ServerlessRestApiProdStage               CREATE_COMPLETE                         
10/29/2018 14:06     AspNetCoreFunctionPutResourcePermissionTest CREATE_COMPLETE                         
10/29/2018 14:06     AspNetCoreFunctionPutResourcePermissionProd CREATE_COMPLETE                         
10/29/2018 14:06     chrisexamples                            CREATE_COMPLETE                         
Stack finished updating with status: CREATE_COMPLETE
   
Output Name                    Value                                             
------------------------------ --------------------------------------------------
ApiURL                         https://q0yq03l8ce.execute-api.eu-central-1.amazonaws.com/Prod/
S3ProxyBucket                  chrisexamples-bucket-************

Notice: if you get errors in output above most definetly you have IAM user policy issues and you must update your user policies with right permissions.

Api for test my app in postman is https://q0yq03l8ce.execute-api.eu-central-1.amazonaws.com/Prod/api/values

Thank you for reading…

 

 

Tags: ,

Copyright by Kristijan Klepač 2018