using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.SystemTextJson; // 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 HelloWorld { public class Function { private static async Task Main() { Func> handler = FunctionHandler; await LambdaBootstrapBuilder.Create(handler, new SourceGeneratorLambdaJsonSerializer()) .Build() .RunAsync(); } private static readonly HttpClient client = new HttpClient(); private static async Task GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var msg = await client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); return msg.Replace("\n",""); } public static async Task FunctionHandler(APIGatewayHttpApiV2ProxyRequest apigProxyEvent, ILambdaContext context) { var location = await GetCallingIP(); var body = new Dictionary { { "message", "hello world" }, { "location", location } }; return new APIGatewayHttpApiV2ProxyResponse { Body = JsonSerializer.Serialize(body), StatusCode = 200, Headers = new Dictionary { { "Content-Type", "application/json" } } }; } } [JsonSerializable(typeof(APIGatewayHttpApiV2ProxyRequest))] [JsonSerializable(typeof(APIGatewayHttpApiV2ProxyResponse))] public partial class MyCustomJsonSerializerContext : JsonSerializerContext { // By using this partial class derived from JsonSerializerContext, we can generate reflection free JSON Serializer code at compile time // which can deserialize our class and properties. However, we must attribute this class to tell it what types to generate serialization code for // See https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-source-generation } }