步骤 2.在项目中添加和更改代码

  1. 打开 Function.cs 并用以下代码替换类代码:

    public class Function
    {
    
    /// <summary>
    /// A simple function that takes a birth date and returns Age in years
    /// </summary>
    /// <param name="input"></param>
    /// <returns>Age is years</returns>
    /// 
    [LambdaSerializer(typeof(SimpleSerializer))]
    public string FunctionHandler(Dictionary<string, int> input)
    {
        var defaultMessage = "Age could not be determined.";
    
        var birthDate = new DateTime(input["year"], input["month"], input["day"]);
        var ageInYears = DateTime.Today.Year - birthDate.Year;
        if (birthDate.DayOfYear > DateTime.Today.DayOfYear)
            ageInYears--;
    
        defaultMessage = $"Age in years: {ageInYears}";
    
        return defaultMessage;
    }
    }
    

你需要在顶部附近添加以下使用语句:

using System.Collections.Generic;
using Amazon.Lambda.Core;
  1. 将文件添加到名为 SimpleSerializer.cs 的项目中
  2. 将以下代码放在该文件中:
using System;

using System.IO;
using Amazon.Lambda.Core;
using Newtonsoft.Json;

namespace AWSLambdaFunctionAgeInYears
{
public class SimpleSerializer : ILambdaSerializer
{
    public T Deserialize<T>(Stream requestStream)
    {
        string text;
        using (var reader = new StreamReader(requestStream))
            text = reader.ReadToEnd();

        try
        {
            return JsonConvert.DeserializeObject<T>(text);
        }
        catch (Exception ex)
        {
            if (typeof(T) == typeof(System.String))
                return (T)Convert.ChangeType(text, typeof(T));

            throw ex;
        }

    }

    public void Serialize<T>(T response, Stream responseStream)
    {
        StreamWriter streamWriter = new StreamWriter(responseStream);
        try
        {
            string text = JsonConvert.SerializeObject(response);
            streamWriter.Write(text);
            streamWriter.Flush();
        }
        catch (Exception ex)
        {
            if (typeof(T) == typeof(System.String))
            {
                streamWriter.Write(response);
                streamWriter.Flush();
                return;
            }

            throw ex;
        }

    }
}
}
  1. 在测试项目中,将 FunctionTest.cs 的第 23 行更改为以下内容:

            var upperCase = function.FunctionHandler(null);
    
  2. 构建你的解决方案 - 你应该没有构建错误。