使用 Lambda 示例 AWS SDK for .NET - AWS SDK 程式碼範例

AWS 文件 AWS SDK 範例 GitHub 存放庫中提供了更多 SDK 範例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 Lambda 示例 AWS SDK for .NET

下列程式碼範例說明如何使用 Lambda 來執行動作和實作常見案例。 AWS SDK for .NET

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數,但您可以在其相關情境和跨服務範例中查看內容中的動作。

Scenarios (案例) 是向您展示如何呼叫相同服務中的多個函數來完成特定任務的程式碼範例。

每個範例都包含一個連結 GitHub,您可以在其中找到如何在內容中設定和執行程式碼的指示。

開始使用

下列程式碼範例示範如何開始使用 Lambda。

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

namespace LambdaActions; using Amazon.Lambda; public class HelloLambda { static async Task Main(string[] args) { var lambdaClient = new AmazonLambdaClient(); Console.WriteLine("Hello AWS Lambda"); Console.WriteLine("Let's get started with AWS Lambda by listing your existing Lambda functions:"); var response = await lambdaClient.ListFunctionsAsync(); response.Functions.ForEach(function => { Console.WriteLine($"{function.FunctionName}\t{function.Description}"); }); } }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考ListFunctions中的。

動作

下列程式碼範例會示範如何使用CreateFunction

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// <summary> /// Creates a new Lambda function. /// </summary> /// <param name="functionName">The name of the function.</param> /// <param name="s3Bucket">The Amazon Simple Storage Service (Amazon S3) /// bucket where the zip file containing the code is located.</param> /// <param name="s3Key">The Amazon S3 key of the zip file.</param> /// <param name="role">The Amazon Resource Name (ARN) of a role with the /// appropriate Lambda permissions.</param> /// <param name="handler">The name of the handler function.</param> /// <returns>The Amazon Resource Name (ARN) of the newly created /// Lambda function.</returns> public async Task<string> CreateLambdaFunctionAsync( string functionName, string s3Bucket, string s3Key, string role, string handler) { // Defines the location for the function code. // S3Bucket - The S3 bucket where the file containing // the source code is stored. // S3Key - The name of the file containing the code. var functionCode = new FunctionCode { S3Bucket = s3Bucket, S3Key = s3Key, }; var createFunctionRequest = new CreateFunctionRequest { FunctionName = functionName, Description = "Created by the Lambda .NET API", Code = functionCode, Handler = handler, Runtime = Runtime.Dotnet6, Role = role, }; var reponse = await _lambdaService.CreateFunctionAsync(createFunctionRequest); return reponse.FunctionArn; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考CreateFunction中的。

下列程式碼範例會示範如何使用DeleteFunction

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// <summary> /// Delete an AWS Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to /// delete.</param> /// <returns>A Boolean value that indicates the success of the action.</returns> public async Task<bool> DeleteFunctionAsync(string functionName) { var request = new DeleteFunctionRequest { FunctionName = functionName, }; var response = await _lambdaService.DeleteFunctionAsync(request); // A return value of NoContent means that the request was processed. // In this case, the function was deleted, and the return value // is intentionally blank. return response.HttpStatusCode == System.Net.HttpStatusCode.NoContent; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考DeleteFunction中的。

下列程式碼範例會示範如何使用GetFunction

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// <summary> /// Gets information about a Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function for /// which to retrieve information.</param> /// <returns>Async Task.</returns> public async Task<FunctionConfiguration> GetFunctionAsync(string functionName) { var functionRequest = new GetFunctionRequest { FunctionName = functionName, }; var response = await _lambdaService.GetFunctionAsync(functionRequest); return response.Configuration; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考GetFunction中的。

下列程式碼範例會示範如何使用Invoke

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// <summary> /// Invoke a Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to /// invoke.</param /// <param name="parameters">The parameter values that will be passed to the function.</param> /// <returns>A System Threading Task.</returns> public async Task<string> InvokeFunctionAsync( string functionName, string parameters) { var payload = parameters; var request = new InvokeRequest { FunctionName = functionName, Payload = payload, }; var response = await _lambdaService.InvokeAsync(request); MemoryStream stream = response.Payload; string returnValue = System.Text.Encoding.UTF8.GetString(stream.ToArray()); return returnValue; }
  • 如需 API 的詳細資訊,請參閱《AWS SDK for .NET API 參考》中的「Invoke」。

下列程式碼範例會示範如何使用ListFunctions

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// <summary> /// Get a list of Lambda functions. /// </summary> /// <returns>A list of FunctionConfiguration objects.</returns> public async Task<List<FunctionConfiguration>> ListFunctionsAsync() { var functionList = new List<FunctionConfiguration>(); var functionPaginator = _lambdaService.Paginators.ListFunctions(new ListFunctionsRequest()); await foreach (var function in functionPaginator.Functions) { functionList.Add(function); } return functionList; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考ListFunctions中的。

下列程式碼範例會示範如何使用UpdateFunctionCode

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// <summary> /// Update an existing Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to update.</param> /// <param name="bucketName">The bucket where the zip file containing /// the Lambda function code is stored.</param> /// <param name="key">The key name of the source code file.</param> /// <returns>Async Task.</returns> public async Task UpdateFunctionCodeAsync( string functionName, string bucketName, string key) { var functionCodeRequest = new UpdateFunctionCodeRequest { FunctionName = functionName, Publish = true, S3Bucket = bucketName, S3Key = key, }; var response = await _lambdaService.UpdateFunctionCodeAsync(functionCodeRequest); Console.WriteLine($"The Function was last modified at {response.LastModified}."); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考UpdateFunctionCode中的。

下列程式碼範例會示範如何使用UpdateFunctionConfiguration

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// <summary> /// Update the code of a Lambda function. /// </summary> /// <param name="functionName">The name of the function to update.</param> /// <param name="functionHandler">The code that performs the function's actions.</param> /// <param name="environmentVariables">A dictionary of environment variables.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> UpdateFunctionConfigurationAsync( string functionName, string functionHandler, Dictionary<string, string> environmentVariables) { var request = new UpdateFunctionConfigurationRequest { Handler = functionHandler, FunctionName = functionName, Environment = new Amazon.Lambda.Model.Environment { Variables = environmentVariables }, }; var response = await _lambdaService.UpdateFunctionConfigurationAsync(request); Console.WriteLine(response.LastModified); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }

案例

以下程式碼範例顯示做法:

  • 建立 IAM 角色和 Lambda 函數,然後上傳處理常式程式碼。

  • 調用具有單一參數的函數並取得結果。

  • 更新函數程式碼並使用環境變數進行設定。

  • 調用具有新參數的函數並取得結果。顯示傳回的執行日誌。

  • 列出您帳戶的函數,然後清理相關資源。

如需詳細資訊,請參閱使用主控台建立 Lambda 函數

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

建立執行 Lambda 動作的方法。

namespace LambdaActions; using Amazon.Lambda; using Amazon.Lambda.Model; /// <summary> /// A class that implements AWS Lambda methods. /// </summary> public class LambdaWrapper { private readonly IAmazonLambda _lambdaService; /// <summary> /// Constructor for the LambdaWrapper class. /// </summary> /// <param name="lambdaService">An initialized Lambda service client.</param> public LambdaWrapper(IAmazonLambda lambdaService) { _lambdaService = lambdaService; } /// <summary> /// Creates a new Lambda function. /// </summary> /// <param name="functionName">The name of the function.</param> /// <param name="s3Bucket">The Amazon Simple Storage Service (Amazon S3) /// bucket where the zip file containing the code is located.</param> /// <param name="s3Key">The Amazon S3 key of the zip file.</param> /// <param name="role">The Amazon Resource Name (ARN) of a role with the /// appropriate Lambda permissions.</param> /// <param name="handler">The name of the handler function.</param> /// <returns>The Amazon Resource Name (ARN) of the newly created /// Lambda function.</returns> public async Task<string> CreateLambdaFunctionAsync( string functionName, string s3Bucket, string s3Key, string role, string handler) { // Defines the location for the function code. // S3Bucket - The S3 bucket where the file containing // the source code is stored. // S3Key - The name of the file containing the code. var functionCode = new FunctionCode { S3Bucket = s3Bucket, S3Key = s3Key, }; var createFunctionRequest = new CreateFunctionRequest { FunctionName = functionName, Description = "Created by the Lambda .NET API", Code = functionCode, Handler = handler, Runtime = Runtime.Dotnet6, Role = role, }; var reponse = await _lambdaService.CreateFunctionAsync(createFunctionRequest); return reponse.FunctionArn; } /// <summary> /// Delete an AWS Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to /// delete.</param> /// <returns>A Boolean value that indicates the success of the action.</returns> public async Task<bool> DeleteFunctionAsync(string functionName) { var request = new DeleteFunctionRequest { FunctionName = functionName, }; var response = await _lambdaService.DeleteFunctionAsync(request); // A return value of NoContent means that the request was processed. // In this case, the function was deleted, and the return value // is intentionally blank. return response.HttpStatusCode == System.Net.HttpStatusCode.NoContent; } /// <summary> /// Gets information about a Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function for /// which to retrieve information.</param> /// <returns>Async Task.</returns> public async Task<FunctionConfiguration> GetFunctionAsync(string functionName) { var functionRequest = new GetFunctionRequest { FunctionName = functionName, }; var response = await _lambdaService.GetFunctionAsync(functionRequest); return response.Configuration; } /// <summary> /// Invoke a Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to /// invoke.</param /// <param name="parameters">The parameter values that will be passed to the function.</param> /// <returns>A System Threading Task.</returns> public async Task<string> InvokeFunctionAsync( string functionName, string parameters) { var payload = parameters; var request = new InvokeRequest { FunctionName = functionName, Payload = payload, }; var response = await _lambdaService.InvokeAsync(request); MemoryStream stream = response.Payload; string returnValue = System.Text.Encoding.UTF8.GetString(stream.ToArray()); return returnValue; } /// <summary> /// Get a list of Lambda functions. /// </summary> /// <returns>A list of FunctionConfiguration objects.</returns> public async Task<List<FunctionConfiguration>> ListFunctionsAsync() { var functionList = new List<FunctionConfiguration>(); var functionPaginator = _lambdaService.Paginators.ListFunctions(new ListFunctionsRequest()); await foreach (var function in functionPaginator.Functions) { functionList.Add(function); } return functionList; } /// <summary> /// Update an existing Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to update.</param> /// <param name="bucketName">The bucket where the zip file containing /// the Lambda function code is stored.</param> /// <param name="key">The key name of the source code file.</param> /// <returns>Async Task.</returns> public async Task UpdateFunctionCodeAsync( string functionName, string bucketName, string key) { var functionCodeRequest = new UpdateFunctionCodeRequest { FunctionName = functionName, Publish = true, S3Bucket = bucketName, S3Key = key, }; var response = await _lambdaService.UpdateFunctionCodeAsync(functionCodeRequest); Console.WriteLine($"The Function was last modified at {response.LastModified}."); } /// <summary> /// Update the code of a Lambda function. /// </summary> /// <param name="functionName">The name of the function to update.</param> /// <param name="functionHandler">The code that performs the function's actions.</param> /// <param name="environmentVariables">A dictionary of environment variables.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> UpdateFunctionConfigurationAsync( string functionName, string functionHandler, Dictionary<string, string> environmentVariables) { var request = new UpdateFunctionConfigurationRequest { Handler = functionHandler, FunctionName = functionName, Environment = new Amazon.Lambda.Model.Environment { Variables = environmentVariables }, }; var response = await _lambdaService.UpdateFunctionConfigurationAsync(request); Console.WriteLine(response.LastModified); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } }

建立可執行該案例的函數。

global using System.Threading.Tasks; global using Amazon.IdentityManagement; global using Amazon.Lambda; global using LambdaActions; global using LambdaScenarioCommon; global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.Hosting; global using Microsoft.Extensions.Logging; global using Microsoft.Extensions.Logging.Console; global using Microsoft.Extensions.Logging.Debug; using Amazon.Lambda.Model; using Microsoft.Extensions.Configuration; namespace LambdaBasics; public class LambdaBasics { private static ILogger logger = null!; static async Task Main(string[] args) { // Set up dependency injection for the Amazon service. using var host = Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => logging.AddFilter("System", LogLevel.Debug) .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information) .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace)) .ConfigureServices((_, services) => services.AddAWSService<IAmazonLambda>() .AddAWSService<IAmazonIdentityManagementService>() .AddTransient<LambdaWrapper>() .AddTransient<LambdaRoleWrapper>() .AddTransient<UIWrapper>() ) .Build(); var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("settings.json") // Load test settings from .json file. .AddJsonFile("settings.local.json", true) // Optionally load local settings. .Build(); logger = LoggerFactory.Create(builder => { builder.AddConsole(); }) .CreateLogger<LambdaBasics>(); var lambdaWrapper = host.Services.GetRequiredService<LambdaWrapper>(); var lambdaRoleWrapper = host.Services.GetRequiredService<LambdaRoleWrapper>(); var uiWrapper = host.Services.GetRequiredService<UIWrapper>(); string functionName = configuration["FunctionName"]!; string roleName = configuration["RoleName"]!; string policyDocument = "{" + " \"Version\": \"2012-10-17\"," + " \"Statement\": [ " + " {" + " \"Effect\": \"Allow\"," + " \"Principal\": {" + " \"Service\": \"lambda.amazonaws.com\" " + " }," + " \"Action\": \"sts:AssumeRole\" " + " }" + "]" + "}"; var incrementHandler = configuration["IncrementHandler"]; var calculatorHandler = configuration["CalculatorHandler"]; var bucketName = configuration["BucketName"]; var incrementKey = configuration["IncrementKey"]; var calculatorKey = configuration["CalculatorKey"]; var policyArn = configuration["PolicyArn"]; uiWrapper.DisplayLambdaBasicsOverview(); // Create the policy to use with the AWS Lambda functions and then attach the // policy to a new role. var roleArn = await lambdaRoleWrapper.CreateLambdaRoleAsync(roleName, policyDocument); Console.WriteLine("Waiting for role to become active."); uiWrapper.WaitABit(15, "Wait until the role is active before trying to use it."); // Attach the appropriate AWS Identity and Access Management (IAM) role policy to the new role. var success = await lambdaRoleWrapper.AttachLambdaRolePolicyAsync(policyArn, roleName); uiWrapper.WaitABit(10, "Allow time for the IAM policy to be attached to the role."); // Create the Lambda function using a zip file stored in an Amazon Simple Storage Service // (Amazon S3) bucket. uiWrapper.DisplayTitle("Create Lambda Function"); Console.WriteLine($"Creating the AWS Lambda function: {functionName}."); var lambdaArn = await lambdaWrapper.CreateLambdaFunctionAsync( functionName, bucketName, incrementKey, roleArn, incrementHandler); Console.WriteLine("Waiting for the new function to be available."); Console.WriteLine($"The AWS Lambda ARN is {lambdaArn}"); // Get the Lambda function. Console.WriteLine($"Getting the {functionName} AWS Lambda function."); FunctionConfiguration config; do { config = await lambdaWrapper.GetFunctionAsync(functionName); Console.Write("."); } while (config.State != State.Active); Console.WriteLine($"\nThe function, {functionName} has been created."); Console.WriteLine($"The runtime of this Lambda function is {config.Runtime}."); uiWrapper.PressEnter(); // List the Lambda functions. uiWrapper.DisplayTitle("Listing all Lambda functions."); var functions = await lambdaWrapper.ListFunctionsAsync(); DisplayFunctionList(functions); uiWrapper.DisplayTitle("Invoke increment function"); Console.WriteLine("Now that it has been created, invoke the Lambda increment function."); string? value; do { Console.Write("Enter a value to increment: "); value = Console.ReadLine(); } while (string.IsNullOrEmpty(value)); string functionParameters = "{" + "\"action\": \"increment\", " + "\"x\": \"" + value + "\"" + "}"; var answer = await lambdaWrapper.InvokeFunctionAsync(functionName, functionParameters); Console.WriteLine($"{value} + 1 = {answer}."); uiWrapper.DisplayTitle("Update function"); Console.WriteLine("Now update the Lambda function code."); await lambdaWrapper.UpdateFunctionCodeAsync(functionName, bucketName, calculatorKey); do { config = await lambdaWrapper.GetFunctionAsync(functionName); Console.Write("."); } while (config.LastUpdateStatus == LastUpdateStatus.InProgress); await lambdaWrapper.UpdateFunctionConfigurationAsync( functionName, calculatorHandler, new Dictionary<string, string> { { "LOG_LEVEL", "DEBUG" } }); do { config = await lambdaWrapper.GetFunctionAsync(functionName); Console.Write("."); } while (config.LastUpdateStatus == LastUpdateStatus.InProgress); uiWrapper.DisplayTitle("Call updated function"); Console.WriteLine("Now call the updated function..."); bool done = false; do { string? opSelected; Console.WriteLine("Select the operation to perform:"); Console.WriteLine("\t1. add"); Console.WriteLine("\t2. subtract"); Console.WriteLine("\t3. multiply"); Console.WriteLine("\t4. divide"); Console.WriteLine("\tOr enter \"q\" to quit."); Console.WriteLine("Enter the number (1, 2, 3, 4, or q) of the operation you want to perform: "); do { Console.Write("Your choice? "); opSelected = Console.ReadLine(); } while (opSelected == string.Empty); var operation = (opSelected) switch { "1" => "add", "2" => "subtract", "3" => "multiply", "4" => "divide", "q" => "quit", _ => "add", }; if (operation == "quit") { done = true; } else { // Get two numbers and an action from the user. value = string.Empty; do { Console.Write("Enter the first value: "); value = Console.ReadLine(); } while (value == string.Empty); string? value2; do { Console.Write("Enter a second value: "); value2 = Console.ReadLine(); } while (value2 == string.Empty); functionParameters = "{" + "\"action\": \"" + operation + "\", " + "\"x\": \"" + value + "\"," + "\"y\": \"" + value2 + "\"" + "}"; answer = await lambdaWrapper.InvokeFunctionAsync(functionName, functionParameters); Console.WriteLine($"The answer when we {operation} the two numbers is: {answer}."); } uiWrapper.PressEnter(); } while (!done); // Delete the function created earlier. uiWrapper.DisplayTitle("Clean up resources"); // Detach the IAM policy from the IAM role. Console.WriteLine("First detach the IAM policy from the role."); success = await lambdaRoleWrapper.DetachLambdaRolePolicyAsync(policyArn, roleName); uiWrapper.WaitABit(15, "Let's wait for the policy to be fully detached from the role."); Console.WriteLine("Delete the AWS Lambda function."); success = await lambdaWrapper.DeleteFunctionAsync(functionName); if (success) { Console.WriteLine($"The {functionName} function was deleted."); } else { Console.WriteLine($"Could not remove the function {functionName}"); } // Now delete the IAM role created for use with the functions // created by the application. Console.WriteLine("Now we can delete the role that we created."); success = await lambdaRoleWrapper.DeleteLambdaRoleAsync(roleName); if (success) { Console.WriteLine("The role has been successfully removed."); } else { Console.WriteLine("Couldn't delete the role."); } Console.WriteLine("The Lambda Scenario is now complete."); uiWrapper.PressEnter(); // Displays a formatted list of existing functions returned by the // LambdaMethods.ListFunctions. void DisplayFunctionList(List<FunctionConfiguration> functions) { functions.ForEach(functionConfig => { Console.WriteLine($"{functionConfig.FunctionName}\t{functionConfig.Description}"); }); } } } namespace LambdaActions; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; public class LambdaRoleWrapper { private readonly IAmazonIdentityManagementService _lambdaRoleService; public LambdaRoleWrapper(IAmazonIdentityManagementService lambdaRoleService) { _lambdaRoleService = lambdaRoleService; } /// <summary> /// Attach an AWS Identity and Access Management (IAM) role policy to the /// IAM role to be assumed by the AWS Lambda functions created for the scenario. /// </summary> /// <param name="policyArn">The Amazon Resource Name (ARN) of the IAM policy.</param> /// <param name="roleName">The name of the IAM role to attach the IAM policy to.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> AttachLambdaRolePolicyAsync(string policyArn, string roleName) { var response = await _lambdaRoleService.AttachRolePolicyAsync(new AttachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } /// <summary> /// Create a new IAM role. /// </summary> /// <param name="roleName">The name of the IAM role to create.</param> /// <param name="policyDocument">The policy document for the new IAM role.</param> /// <returns>A string representing the ARN for newly created role.</returns> public async Task<string> CreateLambdaRoleAsync(string roleName, string policyDocument) { var request = new CreateRoleRequest { AssumeRolePolicyDocument = policyDocument, RoleName = roleName, }; var response = await _lambdaRoleService.CreateRoleAsync(request); return response.Role.Arn; } /// <summary> /// Deletes an IAM role. /// </summary> /// <param name="roleName">The name of the role to delete.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public async Task<bool> DeleteLambdaRoleAsync(string roleName) { var request = new DeleteRoleRequest { RoleName = roleName, }; var response = await _lambdaRoleService.DeleteRoleAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } public async Task<bool> DetachLambdaRolePolicyAsync(string policyArn, string roleName) { var response = await _lambdaRoleService.DetachRolePolicyAsync(new DetachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } } namespace LambdaScenarioCommon; public class UIWrapper { public readonly string SepBar = new('-', Console.WindowWidth); /// <summary> /// Show information about the AWS Lambda Basics scenario. /// </summary> public void DisplayLambdaBasicsOverview() { Console.Clear(); DisplayTitle("Welcome to AWS Lambda Basics"); Console.WriteLine("This example application does the following:"); Console.WriteLine("\t1. Creates an AWS Identity and Access Management (IAM) role that will be assumed by the functions we create."); Console.WriteLine("\t2. Attaches an IAM role policy that has Lambda permissions."); Console.WriteLine("\t3. Creates a Lambda function that increments the value passed to it."); Console.WriteLine("\t4. Calls the increment function and passes a value."); Console.WriteLine("\t5. Updates the code so that the function is a simple calculator."); Console.WriteLine("\t6. Calls the calculator function with the values entered."); Console.WriteLine("\t7. Deletes the Lambda function."); Console.WriteLine("\t7. Detaches the IAM role policy."); Console.WriteLine("\t8. Deletes the IAM role."); PressEnter(); } /// <summary> /// Display a message and wait until the user presses enter. /// </summary> public void PressEnter() { Console.Write("\nPress <Enter> to continue. "); _ = Console.ReadLine(); Console.WriteLine(); } /// <summary> /// Pad a string with spaces to center it on the console display. /// </summary> /// <param name="strToCenter">The string to be centered.</param> /// <returns>The padded string.</returns> public string CenterString(string strToCenter) { var padAmount = (Console.WindowWidth - strToCenter.Length) / 2; var leftPad = new string(' ', padAmount); return $"{leftPad}{strToCenter}"; } /// <summary> /// Display a line of hyphens, the centered text of the title and another /// line of hyphens. /// </summary> /// <param name="strTitle">The string to be displayed.</param> public void DisplayTitle(string strTitle) { Console.WriteLine(SepBar); Console.WriteLine(CenterString(strTitle)); Console.WriteLine(SepBar); } /// <summary> /// Display a countdown and wait for a number of seconds. /// </summary> /// <param name="numSeconds">The number of seconds to wait.</param> public void WaitABit(int numSeconds, string msg) { Console.WriteLine(msg); // Wait for the requested number of seconds. for (int i = numSeconds; i > 0; i--) { System.Threading.Thread.Sleep(1000); Console.Write($"{i}..."); } PressEnter(); } }

定義增量一個數字的 Lambda 處理常式。

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 LambdaIncrement; public class Function { /// <summary> /// A simple function increments the integer parameter. /// </summary> /// <param name="input">A JSON string containing an action, which must be /// "increment" and a string representing the value to increment.</param> /// <param name="context">The context object passed by Lambda containing /// information about invocation, function, and execution environment.</param> /// <returns>A string representing the incremented value of the parameter.</returns> public int FunctionHandler(Dictionary<string, string> input, ILambdaContext context) { if (input["action"] == "increment") { int inputValue = Convert.ToInt32(input["x"]); return inputValue + 1; } else { return 0; } } }

定義可執行算術運算的第二個 Lambda 處理常式。

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 LambdaCalculator; public class Function { /// <summary> /// A simple function that takes two number in string format and performs /// the requested arithmetic function. /// </summary> /// <param name="input">JSON data containing an action, and x and y values. /// Valid actions include: add, subtract, multiply, and divide.</param> /// <param name="context">The context object passed by Lambda containing /// information about invocation, function, and execution environment.</param> /// <returns>A string representing the results of the calculation.</returns> public int FunctionHandler(Dictionary<string, string> input, ILambdaContext context) { var action = input["action"]; int x = Convert.ToInt32(input["x"]); int y = Convert.ToInt32(input["y"]); int result; switch (action) { case "add": result = x + y; break; case "subtract": result = x - y; break; case "multiply": result = x * y; break; case "divide": if (y == 0) { Console.Error.WriteLine("Divide by zero error."); result = 0; } else result = x / y; break; default: Console.Error.WriteLine($"{action} is not a valid operation."); result = 0; break; } return result; } }

無伺服器範例

下列程式碼範例示範如何實作 Lambda 函數,該函數會接收從 Kinesis 串流接收記錄而觸發的事件。此函數會擷取 Kinesis 承載、從 Base64 解碼,並記錄記錄內容。

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 .NET 搭配 Lambda 來使用 Kinesis 事件。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Text; using Amazon.Lambda.Core; using Amazon.Lambda.KinesisEvents; using AWS.Lambda.Powertools.Logging; // 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 KinesisIntegrationSampleCode; public class Function { // Powertools Logger requires an environment variables against your function // POWERTOOLS_SERVICE_NAME [Logging(LogEvent = true)] public async Task FunctionHandler(KinesisEvent evnt, ILambdaContext context) { if (evnt.Records.Count == 0) { Logger.LogInformation("Empty Kinesis Event received"); return; } foreach (var record in evnt.Records) { try { Logger.LogInformation($"Processed Event with EventId: {record.EventId}"); string data = await GetRecordDataAsync(record.Kinesis, context); Logger.LogInformation($"Data: {data}"); // TODO: Do interesting work based on the new data } catch (Exception ex) { Logger.LogError($"An error occurred {ex.Message}"); throw; } } Logger.LogInformation($"Successfully processed {evnt.Records.Count} records."); } private async Task<string> GetRecordDataAsync(KinesisEvent.Record record, ILambdaContext context) { byte[] bytes = record.Data.ToArray(); string data = Encoding.UTF8.GetString(bytes); await Task.CompletedTask; //Placeholder for actual async work return data; } }

下列程式碼範例示範如何實作 Lambda 函數,該函數會接收透過從 DynamoDB 串流接收記錄而觸發的事件。此函數會擷取 DynamoDB 承載並記錄記錄內容。

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 .NET 與 Lambda 一起使用 DynamoDB 事件。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Text.Json; using System.Text; using Amazon.Lambda.Core; using Amazon.Lambda.DynamoDBEvents; // 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 AWSLambda_DDB; public class Function { public void FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context) { context.Logger.LogInformation($"Beginning to process {dynamoEvent.Records.Count} records..."); foreach (var record in dynamoEvent.Records) { context.Logger.LogInformation($"Event ID: {record.EventID}"); context.Logger.LogInformation($"Event Name: {record.EventName}"); context.Logger.LogInformation(JsonSerializer.Serialize(record)); } context.Logger.LogInformation("Stream processing complete."); } }

下列程式碼範例示範如何實作 Lambda 函數,該函數會接收透過將物件上傳至 S3 儲存貯體而觸發的事件。此函數會從事件參數擷取 S3 儲存貯體名稱和物件金鑰,並呼叫 Amazon S3 API 以擷取和記錄物件的內容類型。

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 .NET 搭配 Lambda 來使用 S3 事件。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // 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 S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for {bucket} and {key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning {objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - {e.Message}"); return string.Empty; } } } }

下列程式碼範例示範如何實作 Lambda 函數,該函數會接收來自 SNS 主題的訊息而觸發的事件。函數會從事件參數擷取訊息,並記錄每一則訊息的內容。

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 .NET 搭配 Lambda 來使用 SNS 事件。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Lambda.SNSEvents; // 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 SnsIntegration; public class Function { public async Task FunctionHandler(SNSEvent evnt, ILambdaContext context) { foreach (var record in evnt.Records) { await ProcessRecordAsync(record, context); } context.Logger.LogInformation("done"); } private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context) { try { context.Logger.LogInformation($"Processed record {record.Sns.Message}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } catch (Exception e) { //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ. context.Logger.LogError($"An error occurred"); throw; } } }

下列程式碼範例示範如何實作 Lambda 函數,此函數會接收由 SQS 佇列接收訊息而觸發的事件。函數會從事件參數擷取訊息,並記錄每一則訊息的內容。

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 .NET 搭配 Lambda 來使用 SQS 事件。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Lambda.SQSEvents; // 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 SqsIntegrationSampleCode { public async Task FunctionHandler(SQSEvent evnt, ILambdaContext context) { foreach (var message in evnt.Records) { await ProcessMessageAsync(message, context); } context.Logger.LogInformation("done"); } private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context) { try { context.Logger.LogInformation($"Processed message {message.Body}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } catch (Exception e) { //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ. context.Logger.LogError($"An error occurred"); throw; } } }

下列程式碼範例顯示如何針對接收來自 Kinesis 串流之事件的 Lambda 函數實作部分批次回應。此函數會在回應中報告批次項目失敗,指示 Lambda 稍後重試這些訊息。

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 .NET 搭配 Lambda 報告 Kinesis 批次項目失敗。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Text; using System.Text.Json.Serialization; using Amazon.Lambda.Core; using Amazon.Lambda.KinesisEvents; using AWS.Lambda.Powertools.Logging; // 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 KinesisIntegration; public class Function { // Powertools Logger requires an environment variables against your function // POWERTOOLS_SERVICE_NAME [Logging(LogEvent = true)] public async Task<StreamsEventResponse> FunctionHandler(KinesisEvent evnt, ILambdaContext context) { if (evnt.Records.Count == 0) { Logger.LogInformation("Empty Kinesis Event received"); return new StreamsEventResponse(); } foreach (var record in evnt.Records) { try { Logger.LogInformation($"Processed Event with EventId: {record.EventId}"); string data = await GetRecordDataAsync(record.Kinesis, context); Logger.LogInformation($"Data: {data}"); // TODO: Do interesting work based on the new data } catch (Exception ex) { Logger.LogError($"An error occurred {ex.Message}"); /* Since we are working with streams, we can return the failed item immediately. Lambda will immediately begin to retry processing from this failed item onwards. */ return new StreamsEventResponse { BatchItemFailures = new List<StreamsEventResponse.BatchItemFailure> { new StreamsEventResponse.BatchItemFailure { ItemIdentifier = record.Kinesis.SequenceNumber } } }; } } Logger.LogInformation($"Successfully processed {evnt.Records.Count} records."); return new StreamsEventResponse(); } private async Task<string> GetRecordDataAsync(KinesisEvent.Record record, ILambdaContext context) { byte[] bytes = record.Data.ToArray(); string data = Encoding.UTF8.GetString(bytes); await Task.CompletedTask; //Placeholder for actual async work return data; } } public class StreamsEventResponse { [JsonPropertyName("batchItemFailures")] public IList<BatchItemFailure> BatchItemFailures { get; set; } public class BatchItemFailure { [JsonPropertyName("itemIdentifier")] public string ItemIdentifier { get; set; } } }

下列程式碼範例示範如何針對接收來自 DynamoDB 串流之事件的 Lambda 函數實作部分批次回應。此函數會在回應中報告批次項目失敗,指示 Lambda 稍後重試這些訊息。

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 .NET 報告使用 Lambda 批次項目失敗。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Text.Json; using System.Text; using Amazon.Lambda.Core; using Amazon.Lambda.DynamoDBEvents; // 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 AWSLambda_DDB; public class Function { public StreamsEventResponse FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context) { context.Logger.LogInformation($"Beginning to process {dynamoEvent.Records.Count} records..."); List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new List<StreamsEventResponse.BatchItemFailure>(); StreamsEventResponse streamsEventResponse = new StreamsEventResponse(); foreach (var record in dynamoEvent.Records) { try { var sequenceNumber = record.Dynamodb.SequenceNumber; context.Logger.LogInformation(sequenceNumber); } catch (Exception ex) { context.Logger.LogError(ex.Message); batchItemFailures.Add(new StreamsEventResponse.BatchItemFailure() { ItemIdentifier = record.Dynamodb.SequenceNumber }); } } if (batchItemFailures.Count > 0) { streamsEventResponse.BatchItemFailures = batchItemFailures; } context.Logger.LogInformation("Stream processing complete."); return streamsEventResponse; } }

下列程式碼範例示範如何針對接收來自 SQS 佇列之事件的 Lambda 函數實作部分批次回應。此函數會在回應中報告批次項目失敗,指示 Lambda 稍後重試這些訊息。

AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 .NET 搭配 Lambda 報告 SQS 批次項目失敗。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Lambda.SQSEvents; // 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 sqsSample; public class Function { public async Task<SQSBatchResponse> FunctionHandler(SQSEvent evnt, ILambdaContext context) { List<SQSBatchResponse.BatchItemFailure> batchItemFailures = new List<SQSBatchResponse.BatchItemFailure>(); foreach(var message in evnt.Records) { try { //process your message await ProcessMessageAsync(message, context); } catch (System.Exception) { //Add failed message identifier to the batchItemFailures list batchItemFailures.Add(new SQSBatchResponse.BatchItemFailure{ItemIdentifier=message.MessageId}); } } return new SQSBatchResponse(batchItemFailures); } private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context) { if (String.IsNullOrEmpty(message.Body)) { throw new Exception("No Body in SQS Message."); } context.Logger.LogInformation($"Processed message {message.Body}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } }