How to create an AWS Lambda in .Net


AWS Lambda in .Net


Introduction:


Lambda is based on a principle of Serverless Function-as-as-Service architecture. When we say Serverless, we need not have to configure the server and need zero maintenance of the server. When we say Function-as-as-Service, it means that a code that runs where there is an event can be anything, such as an HTTPS request or an AWS SNS notification.


Why can we not deploy everything in a Lambda and stop using servers such as AWS EC2?


The answer is that Lambda has a few limitations: Lambda is not a magic bullet for all server-related problems. Lambda is expensive when we host a complex service. This is because Lambda internally invokes(starts) a Linux server when it receives an event. It remains ON for a new request for some time, and if it receives a new event, it will use the same instance. This is called 'Warm Start.' On the other hand, if a new event is not received, it will start a new instance called 'Cold Start'. Cold Start is expensive. In addition to this, Lambda's cost per request depends on how long the service took to serve the request: the longer the request, the extension is the Lambda. However, the maximum time Lambda allows to serve a request is 15 minutes. Hence, Lambda is not a single shot solution for all server-related problems.


Steps to create an AWS Lambda in .Net:

Prerequisites:

a. You need an AWS account.

b. Visual Studio.

c. Install AWS toolkit in Visual Studio.

Steps:

a. Open Visual Studio, and create a new project. Select the following (as shown in the image) project template.



b. Provide a name and click Create.



c. You would see the below code in Function.cs. This is the entry point of the Lambda function.

public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context)
        {
      
            context.Logger.LogLine("Get Request\n");

            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body = "Hello AWS Serverless",
                Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } }
            };

            return response;
        }

d. Note that this function accepts APIGatewayProxyRequest as the parameter. For complete details of APIGatewayProxyRequest, check this link - https://github.com/aws/aws-lambda-dotnet/blob/master/Libraries/src/Amazon.Lambda.APIGatewayEvents/APIGatewayProxyRequest.cs 

e. In brief, APIGatewayProxyRequest has members such as Headers, Body, HTTPMethod, etc. 

f. We can write custom(core) logic in this method. For the testing, we can use the Mock lambda Test tool. This will be installed as part of the AWS Toolkit for Visual Studio.

g. For deploying this Lambda to AWS, please check this link- https://www.chaiandwine.info/2021/03/deploying-net-lambda-to-aws.html


Next Recommended Articles- Deploying .Net Lambda and Lambda Authorizer


Happy Coding :)