首页 > 解决方案 > AWS Hello World C# Lambda 函数返回 Json 错误

问题描述

我正在使用默认的 AWS Visual Studio 模板。当我在本地运行测试并使用 AWS Hello World 示例请求时:

在此处输入图像描述

我得到错误:

System.Exception:在 C:\codebuild\tmp\output\src184553615\src\Tools\LambdaTestTool\src 中的 Amazon.Lambda.TestTool.Runtime.LambdaExecutor.BuildParameters(ExecutionRequest request, ILambdaContext context) 处反序列化输入 JSON 以键入字符串时出错\Amazon.Lambda.TestTool\Runtime\LambdaExecutor.cs:C:\codebuild\tmp\output\src184553615\src\Tools\LambdaTestTool\src 中 Amazon.Lambda.TestTool.Runtime.LambdaExecutor.ExecuteAsync(ExecutionRequest request) 的第 215 行\Amazon.Lambda.TestTool\Runtime\LambdaExecutor.cs:第 52 行 ---------------- 内部 1 异常 ------------ System.Reflection。 TargetInvocationException:调用的目标已引发异常。在 System.Reflection.RuntimeMethodInfo 的 System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)。在 C:\codebuild\tmp\output\src184553615\ 中的 Amazon.Lambda.TestTool.Runtime.LambdaExecutor.BuildParameters(ExecutionRequest request, ILambdaContext context) 调用(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfoculture) src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LambdaExecutor.cs:line 203 ---------------- Inner 2 Exception --------- --- Amazon.Lambda.Serialization.SystemTextJson.JsonSerializerException:将 Lambda 事件 JSON 有效负载转换为字符串时出错。必须引用 JSON 字符串,例如“Hello World”才能转换为字符串:无法将 JSON 值转换为 System.String。路径:$ | 行号:0 | BytePositionInLine:1. 在 Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer。Deserialize[T](Stream requestStream) ---------------- Inner 3 Exception ------------ System.Text.Json.JsonException: JSON 值无法转换为 System.String。路径:$ | 行号:0 | BytePositionInLine:1.在 System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& readStack, Utf8JsonReader& reader, Exception ex) at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack) at System.Text.Json System.Text.Json.JsonSerializer.ParseCore(ReadOnlySpan1 utf8Json, Type returnType, JsonSerializerOptions options) at System.Text.Json.JsonSerializer.Deserialize[TValue](ReadOnlySpan1 utf8Json,JsonSerializerOptions 选项)在 Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer.Deserialize[T](Stream requestStream) ---- Inner 4 Exception ------ ------ System.InvalidOperationException:无法将令牌类型“StartObject”的值作为字符串获取。在 System.Text.Json.Utf8JsonReader.GetString() 在 System.Text.Json.Serialization.Converters.JsonConverterString.Read(Utf8JsonReader& 阅读器,类型 typeToConvert,JsonSerializerOptions 选项) 在 System.Text.Json.JsonPropertyInfoNotNullable`4.OnRead(ReadStack&状态,Utf8JsonReader& 阅读器)在 System.Text.Json.JsonPropertyInfo.Read(JsonTokenType tokenType,ReadStack& 状态,Utf8JsonReader& 阅读器)在 System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions 选项,Utf8JsonReader& 阅读器,ReadStack& readStack)

但是,如果我使用“Hello World”作为我的输入字符串,它运行得很好。我绝对想使用 Json 作为输入。我已经验证了 AWS Json 输入并且它验证了。

我究竟做错了什么?

我的代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

using Amazon.Lambda.Core;

// 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 AWSLambda2
{
    public class Function
    {
        
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public string FunctionHandler(String input, ILambdaContext context)
        {

            return input?.ToUpper();
        }
    }
}

.csproj 文件内容:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    <AWSProjectType>Lambda</AWSProjectType>

    <!-- This property makes the build directory similar to a publish directory and helps the AWS .NET Lambda Mock Test Tool find project dependencies. -->
    <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Amazon.Lambda.Core" Version="1.2.0" />
    <PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.1.0" />
  </ItemGroup>
</Project>

标签: c#jsonamazon-web-servicesaws-lambda

解决方案


“错误将输入 JSON 反序列化为类型字符串”错误消息是因为您FunctionHandler指定的方法签名String但您使用 JSON 进行测试。

public string FunctionHandler(String input, ILambdaContext context)

如果您添加了类似于下面的代码来定义与该输入结构匹配的类...

    public class FunctionInput
    {
        public string Key1 { get; set; }
        public string Key2 { get; set; }
        public string Key3 { get; set; }
    }

...然后更改您的方法签名以指定FunctionInput...

public string FunctionHandler(FunctionInput input, ILambdaContext context)

...LambdaSerializer将尝试将 JSON 反序列化为该类。


推荐阅读