

 适用于 .NET 的 AWS SDK V3 已进入维护模式。

我们建议您迁移到 [适用于 .NET 的 AWS SDK V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html)。有关如何迁移的更多详细信息和信息，请参阅我们的[维护模式公告](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/)。

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

# 使用注解来编写 AWS Lambda 函数
<a name="aws-lambda-annotations"></a>

在编写 Lambda 函数时，您有时需要编写大量的处理程序代码，并更新 AWS CloudFormation 模板以及执行其它任务。Lambda 注释是一个框架，有助于减轻 .NET 6 Lambda 函数的负担，从而让使用 C\# 编写 Lambda 的体验更加自然。

如果要举例说明使用 Lambda 注释框架的好处，请考虑以下将两个数字相加的代码片段。

**不使用 Lambda 注释**

```
public class Functions
{
    public APIGatewayProxyResponse LambdaMathPlus(APIGatewayProxyRequest request, ILambdaContext context)
    {
        if (!request.PathParameters.TryGetValue("x", out var xs))
        {
            return new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.BadRequest
            };
        }
        if (!request.PathParameters.TryGetValue("y", out var ys))
        {
            return new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.BadRequest
            };
        }

        var x = int.Parse(xs);
        var y = int.Parse(ys);

        return new APIGatewayProxyResponse
        {
            StatusCode = (int)HttpStatusCode.OK,
            Body = (x + y).ToString(),
            Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } }
        };
    } 
}
```

**使用 Lambda 注释**

```
public class Functions
{
    [LambdaFunction]
    [RestApi("/plus/{x}/{y}")]
    public int Plus(int x, int y)
    {
        return x + y;
    }
}
```

如示例所示，Lambda 注释可以消除对某些 Boilerplate 代码的需求。

有关如何使用该框架以及更多信息，请参阅以下资源：
+ [GitHub 自述](https://github.com/aws/aws-lambda-dotnet/blob/master/Libraries/src/Amazon.Lambda.Annotations/README.md)文件，其中包含有关 Lambda 注释 API 和属性的文档。
+ 有关 Lambda 注释的[博客文章](https://aws.amazon.com/blogs/developer/net-lambda-annotations-framework/)。
+ [https://www.nuget.org/packages/Amazon.Lambda.Annotations](https://www.nuget.org/packages/Amazon.Lambda.Annotations) NuGet 程序包。
+ GitHub 上的[照片资产管理项目](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/PhotoAssetManager)。具体而言，请参阅项目[自述文件](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/dotnetv3/cross-service/PhotoAssetManager/README.md)中的 [PamApiAnnotations](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations) 文件夹和对 Lambda 注释的引用。