步驟 2.在專案中新增和更改程式碼
-
開啟
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;
- 將檔案新增到名為
SimpleSerializer.cs
的專案中 - 將以下程式碼放在該檔案中:
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;
}
}
}
}
-
在測試專案中,將
FunctionTest.cs
的第 23 行更改為以下內容:var upperCase = function.FunctionHandler(null);
-
構建你的解決方案 - 你應該沒有構建錯誤。