

# Build and deploy C\$1 Lambda functions with .zip file archives
Deployment package

A .NET deployment package (.zip file archive) contains your function's compiled assembly along with all of its assembly dependencies. The package also contains a `proj.deps.json` file. This signals to the .NET runtime all of your function's dependencies and a `proj.runtimeconfig.json` file, which is used to configure the runtime.

To deploy individual Lambda functions, you can use the `Amazon.Lambda.Tools` .NET Lambda Global CLI. Using the `dotnet lambda deploy-function` command automatically creates a .zip deployment package and deploys it to Lambda. However, we recommend that you use frameworks like the Amazon Serverless Application Model (Amazon SAM) or the Amazon Cloud Development Kit (Amazon CDK) to deploy your .NET applications to Amazon.

Serverless applications usually comprise a combination of Lambda functions and other managed Amazon Web Services services working together to perform a particular business task. Amazon SAM and Amazon CDK simplify building and deploying Lambda functions with other Amazon Web Services services at scale. The [Amazon SAM template specification](https://docs.amazonaws.cn/serverless-application-model/latest/developerguide/sam-specification.html) provides a simple and clean syntax to describe Lambda functions, APIs, permissions, configurations, and other Amazon resources that make up your serverless application. With the [Amazon CDK](https://docs.amazonaws.cn/cdk/v2/guide/home.html) you define cloud infrastructure as code to help you build reliable, scalable, cost-effective applications in the cloud using modern programming languages and frameworks like .NET. Both the Amazon CDK and the Amazon SAM use the .NET Lambda Global CLI to package your functions.

While it's possible to use [Lambda layers](chapter-layers.md) with functions in C\$1 by [using the .NET Core CLI](csharp-package-cli.md#csharp-layers), we recommend against it. Functions in C\$1 that use layers manually load the shared assemblies into memory during the [Init phase](lambda-runtime-environment.md#runtimes-lifecycle-ib), which can increase cold start times. Instead, include all shared code at compile time to avoid the performance impact of loading assemblies at runtime.

You can find instructions for building and deploying .NET Lambda functions using the Amazon SAM, the Amazon CDK, and the .NET Lambda Global CLI in the following sections.

**Topics**
+ [

# Using the .NET Lambda Global CLI
](csharp-package-cli.md)
+ [

# Deploy C\$1 Lambda functions using Amazon SAM
](csharp-package-sam.md)
+ [

# Deploy C\$1 Lambda functions using Amazon CDK
](csharp-package-cdk.md)
+ [

# Deploy ASP.NET applications
](csharp-package-asp.md)

# Using the .NET Lambda Global CLI
NET Lambda Global CLI

The .NET CLI and the .NET Lambda Global Tools extension (`Amazon.Lambda.Tools`) offer a cross-platform way to create .NET-based Lambda applications, package them, and deploy them to Lambda. In this section, you learn how to create new Lambda .NET projects using the .NET CLI and Amazon Lambda templates, and to package and deploy them using `Amazon.Lambda.Tools`

**Topics**
+ [

## Prerequisites
](#csharp-package-cli-prerequisites)
+ [

## Creating .NET projects using the .NET CLI
](#csharp-package-cli-create)
+ [

## Deploying .NET projects using the .NET CLI
](#csharp-package-cli-deploy)
+ [

## Using Lambda layers with the .NET CLI
](#csharp-layers)

## Prerequisites


**.NET 8 SDK**  
If you haven't already done so, install the [.NET 8](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) SDK and Runtime.

**Amazon Amazon.Lambda.Templates .NET project templates**  
To generate your Lambda function code, use the [https://www.nuget.org/packages/Amazon.Lambda.Templates](https://www.nuget.org/packages/Amazon.Lambda.Templates) NuGet package. To install this template package, run the following command:  

```
dotnet new install Amazon.Lambda.Templates
```

**Amazon Amazon.Lambda.Tools .NET Global CLI tools**  
To create your Lambda functions, you use the [https://www.nuget.org/packages/Amazon.Lambda.Tools](https://www.nuget.org/packages/Amazon.Lambda.Tools) [.NET Global Tools extension](https://aws.amazon.com/blogs/developer/net-core-global-tools-for-aws/). To install Amazon.Lambda.Tools, run the following command:  

```
dotnet tool install -g Amazon.Lambda.Tools
```
For more information about the Amazon.Lambda.Tools .NET CLI extension, see the [Amazon Extensions for .NET CLI](https://github.com/aws/aws-extensions-for-dotnet-cli) repository on GitHub.

## Creating .NET projects using the .NET CLI


In the .NET CLI, you use the `dotnet new` command to create .NET projects from the command line. Lambda offers additional templates using the [https://www.nuget.org/packages/Amazon.Lambda.Templates](https://www.nuget.org/packages/Amazon.Lambda.Templates) NuGet package.

After installing this package, run the following command to see a list of the available templates.

```
dotnet new list
```

To examine details about a template, use the `help` option. For example, to see details about the `lambda.EmptyFunction` template, run the following command.

```
dotnet new lambda.EmptyFunction --help
```

To create a basic template for a .NET Lambda function, use the `lambda.EmptyFunction` template. This creates a simple function that takes a string as input and converts it to upper case using the `ToUpper` method. This template supports the following options: 
+ `--name` – The name of the function.
+ `--region` – The Amazon Region to create the function in.
+ `--profile` – The name of a profile in your Amazon SDK for .NET credentials file. To learn more about credential profiles in .NET, see [Configure Amazon credentials](https://docs.amazonaws.cn/sdk-for-net/v3/developer-guide/net-dg-config-creds.html) in the *Amazon SDK for .NET Developer Guide*.

In this example, we create a new empty function named `myDotnetFunction` using the default profile and Amazon Web Services Region settings:

```
dotnet new lambda.EmptyFunction --name myDotnetFunction
```

This command creates the following files and directories in your project directory.

```
└── myDotnetFunction
    ├── src
    │   └── myDotnetFunction
    │       ├── Function.cs
    │       ├── Readme.md
    │       ├── aws-lambda-tools-defaults.json
    │       └── myDotnetFunction.csproj
    └── test
        └── myDotnetFunction.Tests
            ├── FunctionTest.cs
            └── myDotnetFunction.Tests.csproj
```

Under the `src/myDotnetFunction` directory, examine the following files:
+ **aws-lambda-tools-defaults.json**: This is where you specify the command line options when deploying your Lambda function. For example:

  ```
    "profile" : "default",
    "region" : "us-east-2",
    "configuration" : "Release",
    "function-architecture": "x86_64",
    "function-runtime":"dotnet8",
    "function-memory-size" : 256,
    "function-timeout" : 30,
    "function-handler" : "myDotnetFunction::myDotnetFunction.Function::FunctionHandler"
  ```
+ **Function.cs**: Your Lambda handler function code. It's a C\$1 template that includes the default `Amazon.Lambda.Core` library and a default `LambdaSerializer` attribute. For more information on serialization requirements and options, see [Serialization in C\$1 Lambda functions](csharp-handler.md#csharp-handler-serializer). It also includes a sample function that you can edit to apply your Lambda function code.

  ```
  using Amazon.Lambda.Core;
  
  // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
  [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
  
  namespace myDotnetFunction;
  
  public class Function
  {
  
      /// <summary>
      /// A simple function that takes a string and does a ToUpper
      /// </summary≫
      /// <param name="input"></param>
      /// <param name="context"></param>
      /// <returns></returns>
      public string FunctionHandler(string input, ILambdaContext context)
      {
          return input.ToUpper();
      }
  }
  ```
+ **myDotnetFunction.csproj**: An [MSBuild](https://msdn.microsoft.com/en-us/library/dd393574.aspx) file that lists the files and assemblies that comprise your application.

  ```
  <Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
      <TargetFramework>net8.0</TargetFramework>
      <ImplicitUsings>enable</ImplicitUsings>
      <Nullable>enable</Nullable>
      <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
      <AWSProjectType>Lambda</AWSProjectType>
      <!-- This property makes the build directory similar to a publish directory and helps the AWS .NET Lambda Mock Test Tool find project dependencies. -->
      <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
      <!-- Generate ready to run images during publishing to improve cold start time. -->
      <PublishReadyToRun>true</PublishReadyToRun>
    </PropertyGroup>
    <ItemGroup>
      <PackageReference Include="Amazon.Lambda.Core" Version="2.2.0" />
      <PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.4.0" />
    </ItemGroup>
  </Project>
  ```
+ **Readme**: Use this file to document your Lambda function.

Under the `myfunction/test` directory, examine the following files:
+ **myDotnetFunction.Tests.csproj**: As noted previously, this is an [MSBuild](https://msdn.microsoft.com/en-us/library/dd393574.aspx) file that lists the files and assemblies that comprise your test project. Note also that it includes the `Amazon.Lambda.Core` library, so you can seamlessly integrate any Lambda templates required to test your function.

  ```
  <Project Sdk="Microsoft.NET.Sdk">
     ... 
  
      <PackageReference Include="Amazon.Lambda.Core" Version="2.2.0 " />
     ...
  ```
+ **FunctionTest.cs**: The same C\$1 code template file that it is included in the `src` directory. Edit this file to mirror your function's production code and test it before uploading your Lambda function to a production environment.

  ```
  using Xunit;
  using Amazon.Lambda.Core;
  using Amazon.Lambda.TestUtilities;
  
  using MyFunction;
  
  namespace MyFunction.Tests
  {
      public class FunctionTest
      {
          [Fact]
          public void TestToUpperFunction()
          {
  
              // Invoke the lambda function and confirm the string was upper cased.
              var function = new Function();
              var context = new TestLambdaContext();
              var upperCase = function.FunctionHandler("hello world", context);
  
              Assert.Equal("HELLO WORLD", upperCase);
          }
      }
  }
  ```

## Deploying .NET projects using the .NET CLI


To build your deployment package and deploy it to Lambda, you use the `Amazon.Lambda.Tools` CLI tools. To deploy your function from the files you created in the previous steps, first navigate into the folder containing your function's `.csproj` file.

```
cd myDotnetFunction/src/myDotnetFunction
```

To deploy your code to Lambda as a .zip deployment package, run the following command. Choose your own function name.

```
dotnet lambda deploy-function myDotnetFunction
```

During the deployment, the wizard asks you to select a [Defining Lambda function permissions with an execution role](lambda-intro-execution-role.md). For this example, select the `lambda_basic_role`.

After you have deployed your function, you can test it in the cloud using the `dotnet lambda invoke-function` command. For the example code in the `lambda.EmptyFunction` template, you can test your function by passing in a string using the `--payload` option.

```
dotnet lambda invoke-function myDotnetFunction --payload "Just checking if everything is OK"
```

If your function has been successfully deployed, you should see output similar to the following.

```
dotnet lambda invoke-function myDotnetFunction --payload "Just checking if everything is OK"
Amazon Lambda Tools for .NET Core applications (5.8.0)
Project Home: https://github.com/aws/aws-extensions-for-dotnet-cli, https://github.com/aws/aws-lambda-dotnet

Payload:
"JUST CHECKING IF EVERYTHING IS OK"

Log Tail:
START RequestId: id Version: $LATEST
END RequestId: id
REPORT RequestId: id  Duration: 0.99 ms       Billed Duration: 1 ms         Memory Size: 256 MB     Max Memory Used: 12 MB
```

## Using Lambda layers with the .NET CLI


**Note**  
While it's possible to use [layers](chapter-layers.md) with functions in .NET, we recommend against it. Functions in .NET that use layers manually load the shared assemblies into memory during the `Init` phase, which can increase cold start times. Instead, include all shared code at compile time to take advantage of the built-in optimizations of the .NET compiler.

The .NET CLI supports commands to help you publish layers and deploy C\$1 functions that consume layers. To publish a layer to a specified Amazon S3 bucket, run the following command in the same directory as your `.csproj` file:

```
dotnet lambda publish-layer <layer_name> --layer-type runtime-package-store --s3-bucket <s3_bucket_name>
```

Then, when you deploy your function using the .NET CLI, specify the layer ARN the consume in the following command:

```
dotnet lambda deploy-function <function_name> --function-layers arn:aws:lambda:us-east-1:123456789012:layer:layer-name:1
```

For a complete example of a Hello World function, see the [ blank-csharp-with-layer](https://github.com/awsdocs/aws-lambda-developer-guide/tree/main/sample-apps/blank-csharp-with-layer) sample.

# Deploy C\$1 Lambda functions using Amazon SAM
Amazon SAM

The Amazon Serverless Application Model (Amazon SAM) is a toolkit that helps streamline the process of building and running serverless applications on Amazon. You define the resources for your application in a YAML or JSON template and use the Amazon SAM command line interface (Amazon SAM CLI) to build, package, and deploy your applications. When you build a Lambda function from an Amazon SAM template, Amazon SAM automatically creates a .zip deployment package or container image with your function code and any dependencies you specify. Amazon SAM then deploys your function using an [Amazon CloudFormation stack](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/stacks.html). To learn more about using Amazon SAM to build and deploy Lambda functions, see [Getting started with Amazon SAM](https://docs.amazonaws.cn/serverless-application-model/latest/developerguide/serverless-getting-started.html) in the *Amazon Serverless Application Model Developer Guide*.

The following steps show you how to download, build, and deploy a sample .NET Hello World application using Amazon SAM. This sample application uses a Lambda function and an Amazon API Gateway endpoint to implement a basic API backend. When you send an HTTP GET request to your API Gateway endpoint, API Gateway invokes your Lambda function. The function returns a "hello world" message, along with the IP address of the Lambda function instance that processes your request.

When you build and deploy your application using Amazon SAM, behind the scenes the Amazon SAM CLI uses the `dotnet lambda package` command to package the individual Lambda function code bundles.

## Prerequisites


**.NET 8 SDK**  
Install the [.NET 8](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) SDK and Runtime.

**Amazon SAM CLI version 1.39 or later**  
To learn how to install the latest version of the Amazon SAM CLI, see [Installing the Amazon SAM CLI](https://docs.amazonaws.cn/serverless-application-model/latest/developerguide/install-sam-cli.html).

## Deploy a sample Amazon SAM application


1. Initialize the application using the Hello world .NET template using the following command.

   ```
   sam init --app-template hello-world --name sam-app \
   --package-type Zip --runtime dotnet8
   ```

   This command creates the following files and directories in your project directory.

   ```
   └── sam-app
       ├── README.md
       ├── events
       │   └── event.json
       ├── omnisharp.json
       ├── samconfig.toml
       ├── src
       │   └── HelloWorld
       │       ├── Function.cs
       │       ├── HelloWorld.csproj
       │       └── aws-lambda-tools-defaults.json
       ├── template.yaml
       └── test
           └── HelloWorld.Test
               ├── FunctionTest.cs
               └── HelloWorld.Tests.csproj
   ```

1. Navigate into the directory containing the `template.yaml file`. This file is a tempate that defines the Amazon resources for your application, including your Lambda function and an API Gateway API.

   ```
   cd sam-app
   ```

1. To build the source of your application, run the following command.

   ```
   sam build
   ```

1. To deploy your application to Amazon, run the following command.

   ```
   sam deploy --guided
   ```

   This command packages and deploys your application with the following series of prompts. To accept the default options, press Enter.
**Note**  
For **HelloWorldFunction may not have authorization defined, is this okay?**, be sure to enter `y`.
   + **Stack Name**: The name of the stack to deploy to Amazon CloudFormation. This name must be unique to your Amazon Web Services account and Amazon Web Services Region.
   + **Amazon Web Services Region**: The Amazon Web Services Region you want to deploy your app to.
   + **Confirm changes before deploy**: Select yes to manually review any change sets before Amazon SAM deploys application changes. If you select no, the Amazon SAM CLI automatically deploys application changes.
   + **Allow SAM CLI IAM role creation**: Many Amazon SAM templates, including the Hello world one in this example, create Amazon Identity and Access Management (IAM) roles to give your Lambda functions permission to access other Amazon Web Services services. Select Yes to provide permission to deploy a Amazon CloudFormation stack that creates or modifies IAM roles.
   + **Disable rollback**: By default, if Amazon SAM encounters an error during creation or deployment of your stack, it rolls the stack back to the previous version. Select No to accept this default.
   + **HelloWorldFunction may not have authorization defined, is this okay**: Enter `y`.
   + **Save arguments to samconfig.toml**: Select yes to save your configuration choices. In the future, you can re-run `sam deploy` without parameters to deploy changes to your application.

1. When the deployment of your application is complete, the CLI returns the Amazon Resource Name (ARN) of the Hello World Lambda function and the IAM role created for it. It also displays the endpoint of your API Gateway API. To test your application, open the endpoint in a browser. You should see a response similar to the following.

   ```
   {"message":"hello world","location":"34.244.135.203"}
   ```

1. To delete your resources, run the following command. Note that the API endpoint you created is a public endpoint accessible over the internet. We recommend that you delete this endpoint after testing.

   ```
   sam delete
   ```

## Next steps


To learn more about using Amazon SAM to build and deploy Lambda functions using .NET, see the following resources:
+ The [https://docs.amazonaws.cn/serverless-application-model/latest/developerguide/what-is-sam.html](https://docs.amazonaws.cn/serverless-application-model/latest/developerguide/what-is-sam.html)
+ [Building Serverless .NET Applications with Amazon Lambda and the SAM CLI](https://amazonaws-china.com/blogs/dotnet/building-serverless-net-applications-with-aws-lambda-and-the-sam-cli/)

# Deploy C\$1 Lambda functions using Amazon CDK
Amazon CDK

The Amazon Cloud Development Kit (Amazon CDK) is an open-source software development framework for defining cloud infrastructure as code with modern programming languages and frameworks like .NET. Amazon CDK projects are executed to generate Amazon CloudFormation templates which are then used to deploy your code.

To build and deploy an example Hello world .NET application using the Amazon CDK, follow the instructions in the following sections. The sample application implements a basic API backend consisting of an API Gateway endpoint and a Lambda function. API Gateway invokes the Lambda function when you send an HTTP GET request to the endpoint. The function returns a Hello world message, along with the IP address of the Lambda instance that processes your request.

## Prerequisites


**.NET 8 SDK**  
Install the [.NET 8](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) SDK and Runtime.

**Amazon CDK version 2**  
To learn how to install the latest version of the Amazon CDK see [Getting started with the Amazon CDK](https://docs.amazonaws.cn/cdk/v2/guide/getting_started.html) in the *Amazon Cloud Development Kit (Amazon CDK) v2 Developer Guide*.

## Deploy a sample Amazon CDK application


1. Create a project directory for the sample application and navigate into it.

   ```
   mkdir hello-world
   cd hello-world
   ```

1. Initialize a new Amazon CDK application by running the following command.

   ```
   cdk init app --language csharp
   ```

   The command creates the following files and directories in your project directory

   ```
   ├── README.md
   ├── cdk.json
   └── src
       ├── HelloWorld
       │   ├── GlobalSuppressions.cs
       │   ├── HelloWorld.csproj
       │   ├── HelloWorldStack.cs
       │   └── Program.cs
       └── HelloWorld.sln
   ```

1. Open the `src` directory and create a new Lambda function using the .NET CLI. This is the function you will deploy using the Amazon CDK. In this example, you create a Hello world function named `HelloWorldLambda`using the `lambda.EmptyFunction` template.

   ```
   cd src
   dotnet new lambda.EmptyFunction -n HelloWorldLambda
   ```

   After this step, your directory structure inside your project directory should look like the following.

   ```
   ├── README.md
   ├── cdk.json
   └── src
       ├── HelloWorld
       │   ├── GlobalSuppressions.cs
       │   ├── HelloWorld.csproj
       │   ├── HelloWorldStack.cs
       │   └── Program.cs
       ├── HelloWorld.sln
       └── HelloWorldLambda
           ├── src
           │   └── HelloWorldLambda
           │       ├── Function.cs
           │       ├── HelloWorldLambda.csproj
           │       ├── Readme.md
           │       └── aws-lambda-tools-defaults.json
           └── test
               └── HelloWorldLambda.Tests
                   ├── FunctionTest.cs
                   └── HelloWorldLambda.Tests.csproj
   ```

1. Open the `HelloWorldStack.cs` file from the `src/HelloWorld` directory. Replace the contents of the file with the following code.

   ```
   using Amazon.CDK;
   using Amazon.CDK.AWS.Lambda;
   using Amazon.CDK.AWS.Logs;
   using Constructs;
   
   namespace CdkTest
   {
       public class HelloWorldStack : Stack
       {
           internal HelloWorldStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
           {
               var buildOption = new BundlingOptions()
               {
                   Image = Runtime.DOTNET_8.BundlingImage,
                   User = "root",
                   OutputType = BundlingOutput.ARCHIVED,
                   Command = new string[]{
               "/bin/sh",
                   "-c",
                   " dotnet tool install -g Amazon.Lambda.Tools"+
                   " && dotnet build"+
                   " && dotnet lambda package --output-package /asset-output/function.zip"
                   }
               };
   
                var helloWorldLambdaFunction = new Function(this, "HelloWorldFunction", new FunctionProps
               {
                   Runtime = Runtime.DOTNET_8,
                   MemorySize = 1024,
                   LogRetention = RetentionDays.ONE_DAY,
                   Handler = "HelloWorldLambda::HelloWorldLambda.Function::FunctionHandler",
                   Code = Code.FromAsset("./src/HelloWorldLambda/src/HelloWorldLambda", new Amazon.CDK.AWS.S3.Assets.AssetOptions
                   {
                       Bundling = buildOption
                   }),
               });
           }
       }
   }
   ```

   This is the code to compile and bundle the application code, as well as the definition of the Lambda function itself. the `BundlingOptions` object allows a zip file to be created, along with a set of commands that are used to generate the contents of the zip file. In this instance, the `dotnet lambda package` command is used to compile and generate the zip file.

1. To deploy your application, run the following command.

   ```
   cdk deploy
   ```

1. Invoke your deployed Lambda function using the .NET Lambda CLI.

   ```
   dotnet lambda invoke-function HelloWorldFunction -p "hello world"
   ```

1. After you've finished testing, you can delete the resources you created, unless you want to retain them. Run the following command to delete your resources.

   ```
   cdk destroy
   ```

## Next steps


To learn more about using Amazon CDK to build and deploy Lambda functions using .NET, see the following resources:
+ [Working with the Amazon CDK in C\$1](https://docs.amazonaws.cn/cdk/v2/guide/work-with-cdk-csharp.html)
+ [Build, package, and publish .NET C\$1 Lambda functions with the Amazon CDK](https://amazonaws-china.com/blogs/modernizing-with-aws/build-package-publish-dotnet-csharp-lambda-functions-aws-cdk/)

# Deploy ASP.NET applications
ASP.NET

As well as hosting event-driven functions, you can also use .NET with Lambda to host lightweight ASP.NET applications. You can build and deploy ASP.NET applications using the `Amazon.Lambda.AspNetCoreServer` NuGet package. In this section, you learn how to deploy an ASP.NET web API to Lambda using the .NET Lambda CLI tooling.

**Topics**
+ [

## Prerequisites
](#csharp-package-asp-prerequisites)
+ [

## Deploying an ASP.NET Web API to Lambda
](#csharp-package-asp-deploy-api)
+ [

## Deploying ASP.NET minimal APIs to Lambda
](#csharp-package-asp-deploy-minimal)

## Prerequisites


**.NET 8 SDK**  
Install the [.NET 8](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) SDK and ASP.NET Core Runtime.

**Amazon.Lambda.Tools**  
To create your Lambda functions, you use the [https://www.nuget.org/packages/Amazon.Lambda.Tools](https://www.nuget.org/packages/Amazon.Lambda.Tools) [.NET Global Tools extension](https://aws.amazon.com/blogs/developer/net-core-global-tools-for-aws/). To install Amazon.Lambda.Tools, run the following command:  

```
dotnet tool install -g Amazon.Lambda.Tools
```
For more information about the Amazon.Lambda.Tools .NET CLI extension, see the [Amazon Extensions for .NET CLI](https://github.com/aws/aws-extensions-for-dotnet-cli) repository on GitHub.

**Amazon.Lambda.Templates**  
To generate your Lambda function code, use the [https://www.nuget.org/packages/Amazon.Lambda.Templates](https://www.nuget.org/packages/Amazon.Lambda.Templates) NuGet package. To install this template package, run the following command:  

```
dotnet new --install Amazon.Lambda.Templates
```

## Deploying an ASP.NET Web API to Lambda


To deploy a web API using ASP.NET, you can use the .NET Lambda templates to create a new web API project. Use the following command to initialize a new ASP.NET web API project. In the example command, we name the project `AspNetOnLambda`.

```
dotnet new serverless.AspNetCoreWebAPI -n AspNetOnLambda
```

This command creates the following files and directories in your project directory.

```
.
└── AspNetOnLambda
    ├── src
    │   └── AspNetOnLambda
    │       ├── AspNetOnLambda.csproj
    │       ├── Controllers
    │       │   └── ValuesController.cs
    │       ├── LambdaEntryPoint.cs
    │       ├── LocalEntryPoint.cs
    │       ├── Readme.md
    │       ├── Startup.cs
    │       ├── appsettings.Development.json
    │       ├── appsettings.json
    │       ├── aws-lambda-tools-defaults.json
    │       └── serverless.template
    └── test
        └── AspNetOnLambda.Tests
            ├── AspNetOnLambda.Tests.csproj
            ├── SampleRequests
            │   └── ValuesController-Get.json
            ├── ValuesControllerTests.cs
            └── appsettings.json
```

When Lambda invokes your function, the entry point it uses is the `LambdaEntryPoint.cs` file. The file created by the .NET Lambda template contains the following code.

```
namespace AspNetOnLambda;

public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
{
    protected override void Init(IWebHostBuilder builder)
    {
        builder
            .UseStartup≪Startup≫();
    }

    protected override void Init(IHostBuilder builder)
    {
    }
}
```

The entry point used by Lambda must inherit from one of the three base classes in the `Amazon.Lambda.AspNetCoreServer` package. These three base classes are:
+ `APIGatewayProxyFunction`
+ `APIGatewayHttpApiV2ProxyFunction`
+ `ApplicationLoadBalancerFunction`

The default class used when you create your `LambdaEntryPoint.cs` file using the provided .NET Lambda template is `APIGatewayProxyFunction`. The base class you use in your function depends on which API layer sits in front of your Lambda function.

Each of the three base classes contains a public method named `FunctionHandlerAsync`. The name of this method will form part of the [handler string](csharp-handler.md#csharp-class-library-handlers) Lambda uses to invoke your function. The `FunctionHandlerAsync` method transforms the inbound event payload into the correct ASP.NET format and the ASP.NET response back to a Lambda response payload. For the example `AspNetOnLambda` project shown, the handler string would be as follows.

```
AspNetOnLambda::AspNetOnLambda.LambdaEntryPoint::FunctionHandlerAsync
```

To deploy the API to Lambda, run the following commands to navigate into the directory containing your source code file and deploy your function using Amazon CloudFormation.

```
cd AspNetOnLambda/src/AspNetOnLambda
dotnet lambda deploy-serverless
```

**Tip**  
When you deploy an API using the `dotnet lambda deploy-serverless` command, Amazon CloudFormation gives your Lambda function a name based on the stack name you specify during the deployment. To give your Lambda function a custom name, edit the `serverless.template` file to add a `FunctionName` property to the `AWS::Serverless::Function` resource. See [Name type](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) in the *Amazon CloudFormation User Guide* to learn more.

## Deploying ASP.NET minimal APIs to Lambda


To deploy an ASP.NET minimal API to Lambda, you can use the .NET Lambda templates to create a new minimal API project. Use the following command to initialize a new minimal API project. In this example, we name the project `MinimalApiOnLambda`.

```
dotnet new serverless.AspNetCoreMinimalAPI -n MinimalApiOnLambda
```

The command creates the following files and directories in your project directory.

```
└── MinimalApiOnLambda
    └── src
        └── MinimalApiOnLambda
            ├── Controllers
            │   └── CalculatorController.cs
            ├── MinimalApiOnLambda.csproj
            ├── Program.cs
            ├── Readme.md
            ├── appsettings.Development.json
            ├── appsettings.json
            ├── aws-lambda-tools-defaults.json
            └── serverless.template
```

The `Program.cs` file contains the following code.

```
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

// Add AWS Lambda support. When application is run in Lambda Kestrel is swapped out as the web server with Amazon.Lambda.AspNetCoreServer. This
// package will act as the webserver translating request and responses between the Lambda event source and ASP.NET Core.
builder.Services.AddAWSLambdaHosting(LambdaEventSource.RestApi);

var app = builder.Build();


app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.MapGet("/", () => "Welcome to running ASP.NET Core Minimal API on AWS Lambda");

app.Run();
```

To configure your minimal API to run on Lambda, you may need to edit this code so that requests and responses between Lambda and ASP.NET Core are properly translated. By default, the function is configured for a REST API event source. For an HTTP API or application load balancer, replace `(LambdaEventSource.RestApi)` with one of the following options:
+ `(LambdaEventSource.HttpAPi)`
+ `(LambdaEventSource.ApplicationLoadBalancer)`

To deploy your minimal API to Lambda, run the following commands to navigate into the directory containing your source code file and deploy your function using Amazon CloudFormation.

```
cd MinimalApiOnLambda/src/MinimalApiOnLambda
dotnet lambda deploy-serverless
```