-
Notifications
You must be signed in to change notification settings - Fork 31
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
Changes from 17 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
644b431
Add api example with metrics, logs and tracing
f6c5097
Add Logging part in walkthrough
bc54d81
Add metrics and tracing
bcb174e
Add metrics and tracing
50fcdb6
Some grammary fixes
b576096
Wording and code snippets
eb18172
Reorder sections
65f2542
Merge branch 'awslabs:develop' into develop
swimming-potato 441c130
Add .aws-sam to gitignore
7737524
Add some more text
465a169
Add link in the index documentation page
f2d0b1e
ServerlessApi - Add fixes to unit test
28f91b8
ServerlessApi - Fix bug with adding duplicated Version key on Functio…
b07e7e9
ServerlessApi - Update readme.md code snippets
0db0996
Merge branch 'develop' into develop
hjgraca 7260511
ServerlessApi - add license header and sln file
db10798
Add sam configuraiton file to the gitignore file
29bda6b
ServerlessApi - Change of the solution file name
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
| ||
Microsoft Visual Studio Solution File, Format Version 12.00 | ||
# Visual Studio Version 17 | ||
VisualStudioVersion = 17.0.31903.59 | ||
MinimumVisualStudioVersion = 10.0.40219.1 | ||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{97038683-80A8-4DEC-B494-E774D5D7CA8E}" | ||
EndProject | ||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LambdaPowertoolsAPI", "src\LambdaPowertoolsAPI\LambdaPowertoolsAPI.csproj", "{07541883-22A3-49AB-9A7B-3E2C8CC347F5}" | ||
EndProject | ||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{744F4880-67A3-4BC9-B4E7-D879EC646492}" | ||
EndProject | ||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LambdaPowertoolsAPI.Tests", "test\LambdaPowertoolsAPI.Tests\LambdaPowertoolsAPI.Tests.csproj", "{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}" | ||
EndProject | ||
Global | ||
GlobalSection(SolutionConfigurationPlatforms) = preSolution | ||
Debug|Any CPU = Debug|Any CPU | ||
Release|Any CPU = Release|Any CPU | ||
EndGlobalSection | ||
GlobalSection(SolutionProperties) = preSolution | ||
HideSolutionNode = FALSE | ||
EndGlobalSection | ||
GlobalSection(ProjectConfigurationPlatforms) = postSolution | ||
{07541883-22A3-49AB-9A7B-3E2C8CC347F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU | ||
{07541883-22A3-49AB-9A7B-3E2C8CC347F5}.Debug|Any CPU.Build.0 = Debug|Any CPU | ||
{07541883-22A3-49AB-9A7B-3E2C8CC347F5}.Release|Any CPU.ActiveCfg = Release|Any CPU | ||
{07541883-22A3-49AB-9A7B-3E2C8CC347F5}.Release|Any CPU.Build.0 = Release|Any CPU | ||
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU | ||
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}.Debug|Any CPU.Build.0 = Debug|Any CPU | ||
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}.Release|Any CPU.ActiveCfg = Release|Any CPU | ||
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}.Release|Any CPU.Build.0 = Release|Any CPU | ||
EndGlobalSection | ||
GlobalSection(NestedProjects) = preSolution | ||
{07541883-22A3-49AB-9A7B-3E2C8CC347F5} = {97038683-80A8-4DEC-B494-E774D5D7CA8E} | ||
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F} = {744F4880-67A3-4BC9-B4E7-D879EC646492} | ||
EndGlobalSection | ||
EndGlobal |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
{ | ||
"resource": "/{proxy+}", | ||
"path": "api/values/5", | ||
"httpMethod": "GET", | ||
"body": "{\r\n\t\"message\": \"Hello\"\r\n}", | ||
"isBase64Encoded": false, | ||
"requestContext": { | ||
"requestId": "4749a5a8-93ea-464e-8778-3bffc5f9a35d" | ||
} | ||
} |
71 changes: 71 additions & 0 deletions
71
examples/ServerlessApi/src/LambdaPowertoolsAPI/Controllers/ValuesController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
/* | ||
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). | ||
* You may not use this file except in compliance with the License. | ||
* A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/apache2.0 | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed | ||
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | ||
* express or implied. See the License for the specific language governing | ||
* permissions and limitations under the License. | ||
*/ | ||
|
||
using Microsoft.AspNetCore.Mvc; | ||
using System; | ||
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) | ||
{ | ||
|
||
try | ||
{ | ||
Metrics.AddMetric("SuccessfulRetrieval", 1, MetricUnit.Count); | ||
} | ||
catch (Exception e) | ||
{ | ||
Logger.LogError("Failed to add metric", e); | ||
} | ||
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) | ||
{ | ||
} | ||
} |
81 changes: 81 additions & 0 deletions
81
examples/ServerlessApi/src/LambdaPowertoolsAPI/LambdaEntryPoint.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
/* | ||
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). | ||
* You may not use this file except in compliance with the License. | ||
* A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/apache2.0 | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed | ||
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | ||
* express or implied. See the License for the specific language governing | ||
* permissions and limitations under the License. | ||
*/ | ||
|
||
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) | ||
{ | ||
|
||
if (!_defaultDimensions.ContainsKey("Version")) | ||
_defaultDimensions.Add("Version", lambdaContext.FunctionVersion ?? "Unknown"); | ||
|
||
// Setting the default dimensions. They will be added to every emitted metric. | ||
Metrics.SetDefaultDimensions(_defaultDimensions); | ||
return base.FunctionHandlerAsync(request, lambdaContext); | ||
} | ||
} |
20 changes: 20 additions & 0 deletions
20
examples/ServerlessApi/src/LambdaPowertoolsAPI/LambdaPowertoolsAPI.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
34 changes: 34 additions & 0 deletions
34
examples/ServerlessApi/src/LambdaPowertoolsAPI/LocalEntryPoint.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
/* | ||
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). | ||
* You may not use this file except in compliance with the License. | ||
* A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/apache2.0 | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed | ||
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | ||
* express or implied. See the License for the specific language governing | ||
* permissions and limitations under the License. | ||
*/ | ||
|
||
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>(); | ||
}); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
/* | ||
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). | ||
* You may not use this file except in compliance with the License. | ||
* A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/apache2.0 | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed | ||
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | ||
* express or implied. See the License for the specific language governing | ||
* permissions and limitations under the License. | ||
*/ | ||
|
||
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(); | ||
}); | ||
|
||
} | ||
} |
5 changes: 5 additions & 0 deletions
5
examples/ServerlessApi/src/LambdaPowertoolsAPI/appsettings.Development.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{ | ||
"AWS": { | ||
"Region": "" | ||
} | ||
} |
8 changes: 8 additions & 0 deletions
8
examples/ServerlessApi/src/LambdaPowertoolsAPI/appsettings.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Debug", | ||
"Microsoft.AspNetCore": "Warning" | ||
} | ||
} | ||
} |
14 changes: 14 additions & 0 deletions
14
examples/ServerlessApi/src/LambdaPowertoolsAPI/aws-lambda-tools-defaults.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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": "" | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please rename the solution to PowertoolsServerlessApiExample