

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

# 使用 Lambda 內容物件擷取 C\$1 函數資訊
<a name="csharp-context"></a>

當 Lambda 執行您的函數時，它會將內容物件傳遞至[處理常式](csharp-handler.md)。此物件提供的各項屬性包含了有關叫用、函式以及執行環境的資訊。

**內容屬性**
+ `FunctionName` – Lambda 函數的名稱。
+ `FunctionVersion` – 函數的[版本](configuration-versions.md)。
+ `InvokedFunctionArn` - 用於調用此函數的 Amazon Resource Name (ARN)。指出調用者是否指定版本號或別名。
+ `MemoryLimitInMB` - 分配給函數的記憶體數量。
+ `AwsRequestId` - 調用請求的識別符。
+ `LogGroupName` - 函數的日誌群組。
+ `LogStreamName` - 函數執行個體的記錄串流。
+ `RemainingTime`(`TimeSpan`) - 執行逾時前剩餘的毫秒數。
+ `Identity` - (行動應用程式) 已授權請求的 Amazon Cognito 身分的相關資訊。
+ `ClientContext` - (行動應用程式) 用戶端應用程式提供給 Lambda 的用戶端內容。
+ `Logger` 函式的 [Logger 物件](csharp-logging.md)。

基於監控目的，您可以使用 `ILambdaContext` 物件中的資訊來輸出函數調用的相關資訊。下列程式碼範例說明如何將內容資訊新增至結構化日誌記錄架構。在此範例中，函數會將 `AwsRequestId` 新增至日誌輸出。如果 Lambda 函數即將逾時，函數也會使用 `RemainingTime` 屬性取消傳輸中的任務。

```
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace GetProductHandler;

public class Function
{
    private readonly IDatabaseRepository _repo;
    
    public Function()
    {
        this._repo = new DatabaseRepository();
    }
    
    public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
    {
        Logger.AppendKey("AwsRequestId", context.AwsRequestId);
        
        var id = request.PathParameters["id"];

        using var cts = new CancellationTokenSource();
        
        try
        {
            cts.CancelAfter(context.RemainingTime.Add(TimeSpan.FromSeconds(-1)));
            
            var databaseRecord = await this._repo.GetById(id, cts.Token);
            
            return new APIGatewayProxyResponse 
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body = JsonSerializer.Serialize(databaseRecord)
            };
        }
        catch (Exception ex)
        {
            return new APIGatewayProxyResponse 
            {
                StatusCode = (int)HttpStatusCode.InternalServerError,
                Body = JsonSerializer.Serialize(new { error = ex.Message })
            };
        }
        finally
        {
            cts.Cancel();
        }
    }
}
```