Skip to content

docs: ASP.NET Core WebAPI example(s) #287

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Jun 23, 2023
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ deploy/**
.idea
.vscode
.vs/
.aws-sam

examples/SimpleLambda/.aws-sam
examples/SimpleLambda/samconfig.toml
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ We have provided examples focused specifically on each of the utilities. Each so
* **[Logging example](examples/Logging/)**
* **[Metrics example](examples/Metrics/)**
* **[Tracing example](examples/Tracing/)**
* **[Serverless API example](examples/ServerlessApi/)**


## Other members of the Powertools for AWS Lambda family

Expand Down
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ We have provided a few examples that should you how to use the each of the core
* [Tracing](https://github.com/awslabs/aws-lambda-powertools-dotnet/tree/main/examples/Tracing){target="_blank"} example
* [Logging](https://github.com/awslabs/aws-lambda-powertools-dotnet/tree/main/examples/Logging/){target="_blank"} example
* [Metrics](https://github.com/awslabs/aws-lambda-powertools-dotnet/tree/main/examples/Metrics/){target="_blank"} example
* [Serverless API example](https://github.com/awslabs/aws-lambda-powertools-dotnet/tree/main/examples/ServerlessApi/){target="_blank"} example

## Connect

Expand Down
241 changes: 241 additions & 0 deletions examples/ServerlessApi/Readme.md

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions examples/ServerlessApi/events/event.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"resource": "/{proxy+}",
"path": "api/values",
"httpMethod": "GET",
"body": "{\r\n\t\"message\": \"Hello\"\r\n}",
"isBase64Encoded": false,
"requestContext": {
"requestId": "4749a5a8-93ea-464e-8778-3bffc5f9a35d"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using Microsoft.AspNetCore.Mvc;
using AWS.Lambda.Powertools.Logging;
using AWS.Lambda.Powertools.Tracing;
using AWS.Lambda.Powertools.Metrics;

namespace LambdaPowertoolsAPI.Controllers;

[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
[Tracing(SegmentName = "Values::Get")]
public IEnumerable<string> Get()
{
Logger.LogInformation("Log entry information only about getting values? Or maybe something more ");

return new string[] { "value1", "value2" };
}

// GET api/values/5
[HttpGet("{id}")]
[Tracing(SegmentName = "Values::GetById")]
public string Get(int id)
{

Metrics.AddMetric("SuccessfulRetrieval", 1, MetricUnit.Count);
return "value";
}

// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}

// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}

// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
63 changes: 63 additions & 0 deletions examples/ServerlessApi/src/LambdaPowertoolsAPI/LambdaEntryPoint.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.SystemTextJson;
using AWS.Lambda.Powertools.Logging; // We are adding logging
using AWS.Lambda.Powertools.Tracing; // We are adding tracing
using AWS.Lambda.Powertools.Metrics; // We are adding metrics

namespace LambdaPowertoolsAPI;

/// <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
///
/// LambdaPowertoolsAPI::LambdaPowertoolsAPI.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>();


Console.WriteLine("Startup done");
}


// We are defining some default dimensions.
private Dictionary<string, string> _defaultDimensions = new Dictionary<string, string>{
{"Environment", Environment.GetEnvironmentVariable("ENVIRONMENT") ?? "Unknown"},
{"Runtime",Environment.Version.ToString()}
};

[LambdaSerializer(typeof(DefaultLambdaJsonSerializer))]
[Logging(CorrelationIdPath = CorrelationIdPaths.ApiGatewayRest, LogEvent = true)] // we are enabling logging, it needs to be added on method which have Lambda event
[Tracing] // Adding a tracing attribute here we will see additional function call which might be important in terms of debugging
[Metrics] // Metrics need to be initialized the best place is entry point in opposite on adding attribute on each controller.
public override Task<APIGatewayProxyResponse> FunctionHandlerAsync(APIGatewayProxyRequest request, ILambdaContext lambdaContext)
{
_defaultDimensions.Add("Version", lambdaContext.FunctionVersion);
// Setting the default dimensions. They will be added to every emitted metric.
Metrics.SetDefaultDimensions(_defaultDimensions);
return base.FunctionHandlerAsync(request, lambdaContext);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<OutputType>Exe</OutputType>
<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>
<!-- Generate ready to run images during publishing to improve cold start time. -->
<PublishReadyToRun>true</PublishReadyToRun>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.Lambda.AspNetCoreServer" Version="8.1.0" />
<PackageReference Include="AWS.Lambda.Powertools.Logging" Version="1.1.0" />
<PackageReference Include="AWS.Lambda.Powertools.Metrics" Version="1.2.0" />
<PackageReference Include="AWS.Lambda.Powertools.Tracing" Version="1.1.0" />
</ItemGroup>
</Project>
19 changes: 19 additions & 0 deletions examples/ServerlessApi/src/LambdaPowertoolsAPI/LocalEntryPoint.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
namespace LambdaPowertoolsAPI;

/// <summary>
/// The Main function can be used to run the ASP.NET Core application locally using the Kestrel webserver.
/// </summary>
public class LocalEntryPoint
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
36 changes: 36 additions & 0 deletions examples/ServerlessApi/src/LambdaPowertoolsAPI/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
namespace LambdaPowertoolsAPI;

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"AWS": {
"Region": ""
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft.AspNetCore": "Warning"
}
}
}
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": "",
"region": "",
"configuration": "Release",
"s3-prefix": "LambdaPowertoolsAPI/",
"template": "serverless.template",
"template-parameters": ""
}
10 changes: 10 additions & 0 deletions examples/ServerlessApi/src/LambdaPowertoolsAPI/samconfig.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version = 0.1
[default.deploy.parameters]
stack_name = "aws-lambda-powertools-web-api-sample"
resolve_s3 = true
s3_prefix = "aws-lambda-powertools-web-api-sample"
region = "eu-central-1"
confirm_changeset = true
capabilities = "CAPABILITY_IAM"
disable_rollback = true
image_repositories = []
43 changes: 43 additions & 0 deletions examples/ServerlessApi/src/LambdaPowertoolsAPI/serverless.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
---
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: LambdaPowertoolsAPI::LambdaPowertoolsAPI.LambdaEntryPoint::FunctionHandlerAsync
Runtime: dotnet6
CodeUri: '.'
MemorySize: 256
Timeout: 30
Role:
Tracing: Active
Architectures:
- arm64
Policies:
- AWSLambda_FullAccess
Environment:
Variables:
POWERTOOLS_SERVICE_NAME: aws-lambda-powertools-web-api-sample # This can also be set using the Metrics decorator on your handler [Metrics(Service = "aws-lambda-powertools-web-api-sample"]
POWERTOOLS_LOG_LEVEL: Debug
POWERTOOLS_METRICS_NAMESPACE: AWSLambdaPowertools # This can also be set using the Metrics decorator on your handler [Metrics(Namespace = "AWSLambdaPowertools"]
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/
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EnableDefaultContentItems>False</EnableDefaultContentItems>
</PropertyGroup>
<ItemGroup>
<Content Include=".\SampleRequests\*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Amazon.Lambda.Core" Version="2.1.0" />
<PackageReference Include="Amazon.Lambda.TestUtilities" Version="2.0.0" />
<PackageReference Include="Amazon.Lambda.APIGatewayEvents" Version="2.6.0" />
<PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="3.7.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\LambdaPowertoolsAPI\LambdaPowertoolsAPI.csproj" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"resource": "/{proxy+}",
"path": "/api/values",
"httpMethod": "GET",
"headers": null,
"queryStringParameters": null,
"pathParameters": {
"proxy": "api/values"
},
"stageVariables": null,
"requestContext": {
"accountId": "AAAAAAAAAAAA",
"resourceId": "5agfss",
"stage": "test-invoke-stage",
"requestId": "test-invoke-request",
"identity": {
"cognitoIdentityPoolId": null,
"accountId": "AAAAAAAAAAAA",
"cognitoIdentityId": null,
"caller": "BBBBBBBBBBBB",
"apiKey": "test-invoke-api-key",
"sourceIp": "test-invoke-source-ip",
"cognitoAuthenticationType": null,
"cognitoAuthenticationProvider": null,
"userArn": "arn:aws:iam::AAAAAAAAAAAA:root",
"userAgent": "Apache-HttpClient/4.5.x (Java/1.8.0_102)",
"user": "AAAAAAAAAAAA"
},
"resourcePath": "/{proxy+}",
"httpMethod": "GET",
"apiId": "t2yh6sjnmk"
},
"body": null
}
Loading