Amazon.Lambda.AspNetCoreServer 8.1.1

Prefix Reserved
There is a newer version of this package available.
See the version list below for details.
dotnet add package Amazon.Lambda.AspNetCoreServer --version 8.1.1                
NuGet\Install-Package Amazon.Lambda.AspNetCoreServer -Version 8.1.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Amazon.Lambda.AspNetCoreServer" Version="8.1.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Amazon.Lambda.AspNetCoreServer --version 8.1.1                
#r "nuget: Amazon.Lambda.AspNetCoreServer, 8.1.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Amazon.Lambda.AspNetCoreServer as a Cake Addin
#addin nuget:?package=Amazon.Lambda.AspNetCoreServer&version=8.1.1

// Install Amazon.Lambda.AspNetCoreServer as a Cake Tool
#tool nuget:?package=Amazon.Lambda.AspNetCoreServer&version=8.1.1                

Amazon.Lambda.AspNetCoreServer

This package makes it easy to run ASP.NET Core Web API applications as a Lambda function with API Gateway or an ELB Application Load Balancer. This allows .NET Core developers to create "serverless" applications using the ASP.NET Core Web API framework.

The function takes a request from an API Gateway Proxy or from an Application Load Balancer and converts that request into the classes the ASP.NET Core framework expects and then converts the response from the ASP.NET Core framework into the response body that API Gateway Proxy or Application Load Balancer understands.

Lambda Entry Point

In the ASP.NET Core application add a class that will be the entry point for Lambda to call into the application. Commonly this class is called LambdaEntryPoint. The base class is determined based on where the Lambda functions will be invoked from.

Lambda Involve Base Class
API Gateway REST API APIGatewayProxyFunction
API Gateway WebSocket API APIGatewayProxyFunction
API Gateway HTTP API Payload 1.0 APIGatewayProxyFunction
API Gateway HTTP API Payload 2.0 APIGatewayHttpApiV2ProxyFunction
Application Load Balancer ApplicationLoadBalancerFunction

Note: HTTP API default to payload 2.0 so unless 1.0 is explicitly set the base class should be APIGatewayHttpApiV2ProxyFunction.

Here is an example implementation of the Lamba function in an ASP.NET Core Web API application.

using System.IO;

using Amazon.Lambda.AspNetCoreServer;
using Microsoft.AspNetCore.Hosting;

namespace TestWebApp
{
    /// <summary>
    /// This class extends from APIGatewayProxyFunction which contains the method FunctionHandlerAsync which is the 
    /// actual Lambda function entry point. The Lambda handler field should be set to
    /// 
    /// AWSServerless19::AWSServerless19.LambdaEntryPoint::FunctionHandlerAsync
    /// </summary>
    public class LambdaEntryPoint :

        // The base class must be set to match the AWS service invoking the Lambda function. If not Amazon.Lambda.AspNetCoreServer
        // will fail to convert the incoming request correctly into a valid ASP.NET Core request.
        //
        // API Gateway REST API                         -> Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
        // API Gateway HTTP API payload version 1.0     -> Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
        // API Gateway HTTP API payload version 2.0     -> Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction
        // Application Load Balancer                    -> Amazon.Lambda.AspNetCoreServer.ApplicationLoadBalancerFunction
        // 
        // Note: When using the AWS::Serverless::Function resource with an event type of "HttpApi" then payload version 2.0
        // will be the default and you must make Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction the base class.

        Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
    {
        /// <summary>
        /// The builder has configuration, logging and Amazon API Gateway already configured. The startup class
        /// needs to be configured in this method using the UseStartup<>() method.
        /// </summary>
        /// <param name="builder"></param>
        protected override void Init(IWebHostBuilder builder)
        {
            builder
                .UseStartup<Startup>();
        }
    }
}

The function handler for the Lambda function will be TestWebApp::TestWebApp.LambdaEntryPoint::FunctionHandlerAsync.

Bootstrapping application (IWebHostBuilder vs IHostBuilder)

ASP.NET Core applications are bootstrapped by using a host builder. The host builder is used to configure all of the required services needed to run the ASP.NET Core application. With Amazon.Lambda.AspNetCoreServer there are multiple options for customizing the bootstrapping and they vary between targeted versions of .NET Core.

ASP.NET Core 3.1

ASP.NET Core 3.1 uses the generic IHostBuilder to bootstrap the application. In a typical ASP.NET Core 3.1 application the Program.cs file will bootstrap the application using IHostBuilder like the following snippet shows. As part of creating the IHostBuilder an IWebHostBuilder is created by the ConfigureWebHostDefaults method.

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

Amazon.Lambda.AspNetCoreServer creates this IHostBuilder and configures all of the default settings needed to run the ASP.NET Core application in Lambda.

There are two Init methods that can be overridden to customize the IHostBuilder. The most common customization is to override the Init(IWebHostBuilder) method and set the startup class via the UseStartup method. To customize the IHostBuilder then override the Init(IHostBuilder). Do not call ConfigureWebHostDefaults when overriding Init(IHostBuilder) because Amazon.Lambda.AspNetCoreServer will call ConfigureWebHostDefaults when creating the IHostBuilder. By calling ConfigureWebHostDefaults in the Init(IHostBuilder) method, the IWebHostBuilder will be configured twice.

If you want complete control over creating the IHostBuilder then override the CreateHostBuilder method. When overriding the CreateHostBuilder method neither of the Init methods will be called unless the override calls the base implementation. When overriding CreateHostBuilder it is recommended to call ConfigureWebHostLambdaDefaults instead of ConfigureWebHostDefaults to configure the IWebHostBuilder for Lambda.

If the CreateWebHostBuilder is overridden in an ASP.NET Core 3.1 application then only the IWebHostBuilder is used for bootstrapping using the same pattern that ASP.NET Core 2.1 applications use. CreateHostBuilder and Init(IHostBuilder) will not be called when CreateWebHostBuilder is overridden.

ASP.NET Core 2.1

ASP.NET Core 2.1 applications are bootstrapped with the IWebHostBuilder type. Amazon.Lambda.AspNetCoreServer will create an instance of IWebHostBuilder and it can be customized by overriding the Init(IWebHostBuilder) method. The most common customization is configuring the startup class via the UseStartup method.

If you want complete control over creating the IWebHostBuilder then override the CreateWebHostBuilder method. When overriding the CreateWebHostBuilder method the Init(IWebHostBuilder) method will not be called unless the override calls the base implementation or explicitly calls the Init(IWebHostBuilder) method.

Access to Lambda Objects from HttpContext

The original lambda request object and the ILambdaContext object can be accessed from the HttpContext.Items collection.

Constant Object
AbstractAspNetCoreFunction.LAMBDA_CONTEXT ILambdaContext
AbstractAspNetCoreFunction.LAMBDA_REQUEST_OBJECT <ul><li>APIGatewayProxyFunction → APIGatewayProxyRequest</li><li>APIGatewayHttpApiV2ProxyFunction → APIGatewayHttpApiV2ProxyRequest</li><li>ApplicationLoadBalancerFunction → ApplicationLoadBalancerRequest</li></ul>

JSON Serialization

Starting with version 5.0.0 when targeting .NET Core 3.1 Amazon.Lambda.Serialization.SystemTextJson. When targeting previous versions of .NET Core or using a version of Amazon.Lambda.AspNetCoreServer before 5.0.0 will use Amazon.Lambda.Serialization.Json.

Web App Path Base

By default this package configure the path base for incoming requests to be root of the API Gateway Stage or Application Load Balancer.

If you want to treat a subresource in the resource path to be the path base you will need to modify how requests are marshalled into ASP.NET Core. For example if the listener of an Application Load Balancer points to a Lambda Target Group for requests starting with /webapp/* and you want to call a controller api/values ASP.NET Core will think the resource you want to access is /webapp/api/values which will return a 404 NotFound.

In the LambdaEntryPoint class you can override the PostMarshallRequestFeature method to add custom logic to how the path base is computed. In the example below it configures the path base to be /webapp/. When the Application Load balancer sends in a request with the resource path set to /webapp/api/values. This code configures the ASP.NET Core request to have the path base set to /webapp/ and the path to /api/values.

    public class LambdaEntryPoint : ApplicationLoadBalancerFunction
    {
        protected override void Init(IWebHostBuilder builder)
        {
            builder
                .UseStartup<Startup>();
        }

        protected override void PostMarshallRequestFeature(IHttpRequestFeature aspNetCoreRequestFeature, ApplicationLoadBalancerRequest lambdaRequest, ILambdaContext lambdaContext)
        {
            aspNetCoreRequestFeature.PathBase = "/webapp/";

            // The minus one is ensure path is always at least set to `/`
            aspNetCoreRequestFeature.Path = 
                aspNetCoreRequestFeature.Path.Substring(aspNetCoreRequestFeature.PathBase.Length - 1);
            lambdaContext.Logger.LogLine($"Path: {aspNetCoreRequestFeature.Path}, PathBase: {aspNetCoreRequestFeature.PathBase}");
        }
    }

Supporting Binary Response Content

The interface between the API Gateway/Application Load Balancer and Lambda assumes response content to be returned as a UTF-8 string. In order to return binary content it is necessary to encode the raw response content in Base64 and to set a flag in the response object that Base64-encoding has been applied.

In order to facilitate this mechanism, the base class maintains a registry of MIME content types and how they should be transformed before being returned to the calling API Gateway or Application Load Balancer. For any binary content types that are returned by your application, you should register them for Base64 tranformation and then the framework will take care of intercepting any such responses and making an necessary transformations to preserve the binary content. For example:

using System.IO;

using Amazon.Lambda.AspNetCoreServer;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace TestWebApp
{
    public class LambdaFunction : APIGatewayProxyFunction
    {
        protected override void Init(IWebHostBuilder builder)
        {
            // Register any MIME content types you want treated as binary
            RegisterResponseContentEncodingForContentType("application/octet-stream",
                    ResponseContentEncoding.Base64);
            
            // ...
        }
    }

    // In your controller actions, be sure to provide a Content Type for your responses
    public class LambdaController : Controller
    {
        public IActionResult GetBinary()
        {
            var binData = new byte[] { 0x00, 0x01, 0x02, 0x03 };
 
            return base.File(binData, "application/octet-stream");
        }
    }
}

IMPORTANT - Registering Binary Response with API Gateway

In order to use this mechanism to return binary response content, in addition to registering any binary MIME content types that will be returned by your application, it also necessary to register those same content types with the API Gateway using either the console or the REST interface.

For Application Load Balancer this step is not necessary.

Default Registered Content Types

By default several commonly used MIME types that are typically used with Web API services are already pre-registered. You can make use of these content types without any further changes in your code, however, for any binary content types, you do still need to make the necessary adjustments in the API Gateway as described above.

MIME Content Type Response Content Encoding
text/plain Default (UTF-8)
text/xml Default (UTF-8)
application/xml Default (UTF-8)
application/json Default (UTF-8)
text/html Default (UTF-8)
text/css Default (UTF-8)
text/javascript Default (UTF-8)
text/ecmascript Default (UTF-8)
text/markdown Default (UTF-8)
text/csv Default (UTF-8)
application/octet-stream Base64
image/png Base64
image/gif Base64
image/jpeg Base64
application/zip Base64
application/pdf Base64
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.1 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (22)

Showing the top 5 NuGet packages that depend on Amazon.Lambda.AspNetCoreServer:

Package Downloads
Amazon.Lambda.AspNetCoreServer.Hosting

Package for running ASP.NET Core applications using the Minimal API style as a AWS Lambda function.

Bisque.Aws

Tool to generate AWS CloudFormation json templates for Amazon AWS CloudFormation

MhLabs.APIGatewayLambdaProxy

Package Description

MhLabs.APIGatewayLambdaProxy.Logging

Package Description

Albelli.Templates.Amazon.Core

A structured template to create AWS Lambda in C#. It supports ASP.NET Core project pipeline, but can handle any AWS lambda input

GitHub repositories (8)

Showing the top 5 popular GitHub repositories that depend on Amazon.Lambda.AspNetCoreServer:

Repository Stars
aws/aws-lambda-dotnet
Libraries, samples and tools to help .NET Core developers develop AWS Lambda functions.
getsentry/sentry-dotnet
Sentry SDK for .NET
exceptionless/Exceptionless.Net
Exceptionless clients for the .NET platform
aws/aws-extensions-for-dotnet-cli
Extensions to the dotnet CLI to simplify the process of building and publishing .NET Core applications to AWS services
PowerShellOrg/tug
Open-source, cross-platform Pull/Reporting Server for DSC
Version Downloads Last updated
9.0.2 1,759 11/20/2024
9.0.1 326,813 9/5/2024
9.0.0 1,445,482 2/16/2024
8.1.1 714,091 11/14/2023
8.1.0 2,410,131 3/24/2023
8.0.0 525,123 2/13/2023
7.3.0 1,231,005 12/7/2022
7.2.0 3,057,828 5/18/2022
7.1.0 841,624 3/15/2022
7.0.1 986,960 12/13/2021
7.0.0 70,477 11/22/2021
6.1.0 285,831 11/5/2021
6.0.3 1,216,175 7/15/2021
6.0.2 333,620 5/12/2021
6.0.1 249,118 4/30/2021
6.0.0 280,435 4/5/2021
5.3.1 549,835 2/19/2021
5.3.0 649,131 1/11/2021
5.2.0 712,346 10/21/2020
5.1.6 275,175 9/30/2020
5.1.5 108,422 9/17/2020
5.1.4 45,417 9/10/2020
5.1.3 244,113 7/23/2020
5.1.2 183,373 6/25/2020
5.1.1 715,975 5/4/2020
5.1.0 297,976 4/28/2020
5.0.0 423,811 3/31/2020
4.1.0 331,900 12/18/2019
4.0.0 168,552 10/25/2019
3.1.0 461,245 6/20/2019
3.0.4 162,724 5/1/2019
3.0.3 128,747 3/8/2019
3.0.2 182,322 2/21/2019
3.0.1 28,843 2/8/2019
3.0.0 5,311 2/7/2019
2.1.0 498,023 9/25/2018
2.0.4 367,747 5/29/2018
2.0.3 53,800 5/1/2018
2.0.2 24,232 3/26/2018
2.0.1 51,729 2/12/2018
2.0.0 58,595 1/15/2018
0.10.2-preview1 21,992 6/23/2017
0.10.1-preview1 37,133 4/28/2017
0.10.0-preview1 1,041 4/26/2017
0.9.0-preview1 18,695 2/10/2017
0.8.6-preview1 1,825 1/27/2017
0.8.5-preview1 996 1/26/2017
0.8.4-preview1 1,349 1/17/2017
0.8.3-preview1 1,016 1/14/2017
0.8.2-preview1 1,158 12/21/2016
0.8.1-preview1 1,216 12/2/2016
0.8.0-preview1 6,909 12/1/2016