Skip to content

Commit

Permalink
Merge pull request #1081 from aws/normj/net6-aspnetcoreminimal-blueprint
Browse files Browse the repository at this point in the history
Add ASP.NET Core Minimal API blueprint
  • Loading branch information
normj authored Feb 17, 2022
2 parents f38d21c + 0166fdc commit 1eb9c64
Show file tree
Hide file tree
Showing 10 changed files with 278 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"display-name": "ASP.NET Core Minimal API",
"system-name": "AspNetCoreMinimalAPI",
"description": "Serverless ASP.NET Core Minimal API",
"sort-order": 150,
"hidden-tags": [
"C#",
"ServerlessProject"
],
"tags": [
"AspNetCore",
"TopLevelStatements"
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{
"$schema": "http://json.schemastore.org/template",
"author": "AWS",
"classifications": [
"AWS",
"Lambda",
"Serverless"
],
"name": "Lambda ASP.NET Core Minimal API",
"identity": "AWS.Lambda.Serverless.AspNetCoreMinimalAPI.CSharp",
"groupIdentity": "AWS.Lambda.Serverless.AspNetCoreMinimalAPI",
"shortName": "serverless.AspNetCoreMinimalAPI",
"tags": {
"language": "C#",
"type": "project"
},
"sourceName": "BlueprintBaseName.1",
"preferNameDirectory": true,
"symbols": {
"profile": {
"type": "parameter",
"description": "The AWS credentials profile set in aws-lambda-tools-defaults.json and used as the default profile when interacting with AWS.",
"datatype": "string",
"replaces": "DefaultProfile",
"defaultValue": ""
},
"region": {
"type": "parameter",
"description": "The AWS region set in aws-lambda-tools-defaults.json and used as the default region when interacting with AWS.",
"datatype": "string",
"replaces": "DefaultRegion",
"defaultValue": ""
},
"safe-sourcename": {
"type": "generated",
"generator": "coalesce",
"parameters": {
"sourceVariableName": "safe_namespace",
"fallbackVariableName": "safe_name"
},
"replaces": "BlueprintBaseName._1"
}
},
"primaryOutputs": [
{
"path": "./src/BlueprintBaseName.1/BlueprintBaseName.1.csproj"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.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>

<!-- By enabling trimming the deployment bundle size can be reduced and improve Lambda cold start time. Extra testing is required
enabling feature to ensure the .NET compilier does not remove required code.
<PublishTrimmed>true</PublishTrimmed> -->

<!-- Generate ready to run images during publishing to improvement cold starts. -->
<PublishReadyToRun>true</PublishReadyToRun>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Amazon.Lambda.AspNetCoreServer.Hosting" Version="1.0.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using Microsoft.AspNetCore.Mvc;

namespace BlueprintBaseName._1.Controllers;

[ApiController]
[Route("[controller]")]
public class CalculatorController : ControllerBase
{
private readonly ILogger<CalculatorController> _logger;

public CalculatorController(ILogger<CalculatorController> logger)
{
_logger = logger;
}

[HttpGet("add/{x}/{y}")]
public int Add(int x, int y)
{
_logger.LogInformation($"{x} plus {y} is {x + y}");
return x + y;
}

[HttpGet("substract/{x}/{y}")]
public int Substract(int x, int y)
{
_logger.LogInformation($"{x} substract {y} is {x - y}");
return x - y;
}

[HttpGet("multiply/{x}/{y}")]
public int Multiply(int x, int y)
{
_logger.LogInformation($"{x} multiply {y} is {x * y}");
return x * y;
}

[HttpGet("divide/{x}/{y}")]
public int Divide(int x, int y)
{
_logger.LogInformation($"{x} divide {y} is {x / y}");
return x / y;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
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();
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# ASP.NET Core Minimal API Serverless Application

This project shows how to run an ASP.NET Core Web API project as an AWS Lambda exposed through Amazon API Gateway. The NuGet package [Amazon.Lambda.AspNetCoreServer](https://www.nuget.org/packages/Amazon.Lambda.AspNetCoreServer) contains a Lambda function that is used to translate requests from API Gateway into the ASP.NET Core framework and then the responses from ASP.NET Core back to API Gateway.


For more information about how the Amazon.Lambda.AspNetCoreServer package works and how to extend its behavior view its [README](https://github.com/aws/aws-lambda-dotnet/blob/master/Libraries/src/Amazon.Lambda.AspNetCoreServer/README.md) file in GitHub.

## Executable Assembly ##

.NET Lambda projects that use C# top level statements like this project must be deployed as an executable assembly instead of a class library. To indicate to Lambda that the .NET function is an executable assembly the
Lambda function handler value is set to the .NET Assembly name. This is different then deploying as a class library where the function handler string includes the assembly, type and method name.

To deploy as an executable assembly the Lambda runtime client must be started to listen for incoming events to process. For an ASP.NET Core application the Lambda runtime client is started by included the
`Amazon.Lambda.AspNetCoreServer.Hosting` NuGet package and calling `AddAWSLambdaHosting(LambdaEventSource.HttpApi)` passing in the event source while configuring the services of the application. The
event source can be API Gateway REST API and HTTP API or Application Load Balancer.

### Project Files ###

* serverless.template - an AWS CloudFormation Serverless Application Model template file for declaring your Serverless functions and other AWS resources
* aws-lambda-tools-defaults.json - default argument settings for use with Visual Studio and command line deployment tools for AWS
* Program.cs - entry point to the application that contains all of the top level statements initializing the ASP.NET Core application.
The call to `AddAWSLambdaHosting` configures the application to work in Lambda when it detects Lambda is the executing environment.
* Controllers\CalculatorController - example Web API controller

You may also have a test project depending on the options selected.

## Here are some steps to follow from Visual Studio:

To deploy your Serverless application, right click the project in Solution Explorer and select *Publish to AWS Lambda*.

To view your deployed application open the Stack View window by double-clicking the stack name shown beneath the AWS CloudFormation node in the AWS Explorer tree. The Stack View also displays the root URL to your published application.

## Here are some steps to follow to get started from the command line:

Once you have edited your template and code you can deploy your application using the [Amazon.Lambda.Tools Global Tool](https://github.com/aws/aws-extensions-for-dotnet-cli#aws-lambda-amazonlambdatools) from the command line.

Install Amazon.Lambda.Tools Global Tools if not already installed.
```
dotnet tool install -g Amazon.Lambda.Tools
```

If already installed check if new version is available.
```
dotnet tool update -g Amazon.Lambda.Tools
```

Deploy application
```
cd "BlueprintBaseName.1/src/BlueprintBaseName.1"
dotnet lambda deploy-serverless
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"Information": [
"This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
"To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",
"dotnet lambda help",
"All the command line options for the Lambda command can be specified in this file."
],
"profile": "DefaultProfile",
"region": "DefaultRegion",
"configuration": "Release",
"s3-prefix": "BlueprintBaseName.1/",
"template": "serverless.template",
"template-parameters": ""
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
"AWSTemplateFormatVersion": "2010-09-09",
"Transform": "AWS::Serverless-2016-10-31",
"Description": "An AWS Serverless Application that uses the ASP.NET Core framework running in Amazon Lambda.",
"Parameters": {},
"Conditions": {},
"Resources": {
"AspNetCoreFunction": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "BlueprintBaseName.1",
"Runtime": "dotnet6",
"CodeUri": "",
"MemorySize": 256,
"Timeout": 30,
"Role": null,
"Policies": [
"AWSLambda_FullAccess"
],
"Events": {
"ProxyResource": {
"Type": "Api",
"Properties": {
"Path": "/{proxy+}",
"Method": "ANY"
}
},
"RootResource": {
"Type": "Api",
"Properties": {
"Path": "/",
"Method": "ANY"
}
}
}
}
}
},
"Outputs": {
"ApiURL": {
"Description": "API endpoint URL for Prod environment",
"Value": {
"Fn::Sub": "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"
}
}
}
}

0 comments on commit 1eb9c64

Please sign in to comment.