使用 Amazon SDK for .NET 的 Lambda 示例 - Amazon SDK for .NET
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 Amazon SDK for .NET 的 Lambda 示例

以下代码示例演示了如何将Amazon SDK for .NET 与 Lambda 结合使用,以执行操作和实现常见场景。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景是指显示如何通过在同一服务中调用多个函数来完成特定任务的代码示例。

每个示例都包含一个指向的链接 GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

开始使用

以下代码示例演示了如何开始使用 Lambda。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 的详细信息,请参阅 Amazon SDK for .NETAPI 参考ListFunctions中的。

操作

以下代码示例演示了如何创建 Lambda 函数。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <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 的详细信息,请参阅 Amazon SDK for .NETAPI 参考CreateFunction中的。

以下代码示例演示了如何删除 Lambda 函数。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <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 的详细信息,请参阅 Amazon SDK for .NETAPI 参考DeleteFunction中的。

以下代码示例演示了如何获取 Lambda 函数。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <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 的详细信息,请参阅 Amazon SDK for .NETAPI 参考GetFunction中的。

以下代码示例演示了如何调用 Lambda 函数。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <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 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 Invoke

以下代码示例演示了如何列出 Lambda 函数。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <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 的详细信息,请参阅 Amazon SDK for .NETAPI 参考ListFunctions中的。

以下代码示例演示了如何更新 Lambda 函数代码。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <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 的详细信息,请参阅 Amazon SDK for .NETAPI 参考UpdateFunctionCode中的。

以下代码示例演示了如何更新 Lambda 函数配置。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <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 函数

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

创建用于执行 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 解码,并记录下记录内容。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

通过 .NET 将 Kinesis 事件与 Lambda 结合使用。

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 函数,该函数接收将对象上传到 S3 桶时触发的事件。该函数从事件参数中检索 S3 桶名称和对象密钥,并调用 Amazon S3 API 来检索和记录对象的内容类型。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

使用 .NET 将 S3 事件与 Lambda 结合使用。

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 主题的消息而触发的事件。该函数从事件参数检索消息并记录每条消息的内容。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

使用 .NET 将 SNS 事件与 Lambda 结合使用。

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 队列收到消息时触发的事件。该函数从事件参数检索消息并记录每条消息的内容。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

通过 .NET 将 SQS 事件与 Lambda 结合使用。

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 稍后重试这些消息。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

报告使用 .NET 进行 Lambda Kinesis 批处理项目失败。

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; } } }

以下代码示例演示如何为从 SQS 队列接收事件的 Lambda 函数实现部分批处理响应。该函数在响应中报告批处理项目失败,并指示 Lambda 稍后重试这些消息。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

报告使用 .NET 进行 Lambda SQS 批处理项目失败。

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; } }