c# - 从 C# 中的 AWS Lambda 函数返回 JSON

标签 c# aws-lambda

问题:输出看起来像这样 [{\"FirstName\":\"William Smith\"}]"

问题:如何从用 C# 编写的 AWS Lambda 函数返回格式正确的 JSON 字符串?

详细信息:

  1. 我有一个用 C# 编写的 AWS Lambda 函数
  2. 返回类型为“字符串”
  3. 目的是将返回类型作为 JSON 使用
  4. 这是 C# Lambda 函数编码返回的内容:

    string TestJsonEvent = "[{\"FirstName\":\"William Smith\"}]"; 返回 TestJsonEvent;

当 Lambda 函数执行时;它返回: "[{\"名字\":\"威廉·史密斯\"}]"

  1. 即使这个变体也返回相同的结果:

    string TestJsonEvent = @"[{""FirstName"":""William Smith""}]"; 返回 TestJsonEvent;

最佳答案

Amazon 在他们的 announcement for C# support 中有示例和 Lambda Function Handler文档。

相关位:

Handling Standard Data Types

All other types, as listed below, require you to specify a serializer.

  • Primitive .NET types (such as string or int).
  • Collections and maps - IList, IEnumerable, IList, Array, IDictionary, IDictionary
  • POCO types (Plain old CLR objects)
  • Predefined AWS event types
  • For asynchronous invocations the return-type will be ignored by Lambda. The return type may be set to void in such cases.
  • If you are using .NET asynchronous programming, the return type can be Task and Task types and use async and await keywords. For more information, see Using Async in C# Functions with AWS Lambda.

Unless your function input and output parameters are of type System.IO.Stream, you will need to serialize them. AWS Lambda provides a default serializer that can be applied at the assembly or method level of your application, or you can define your own by implementing the ILambdaSerializer interface provided by the Amazon.Lambda.Core library.

To add the default serializer attribute to a method, first add a dependency on Amazon.Lambda.Serialization.Json[...]

安装 Amazon.Lambda.Serialization.Json [1] NuGet 打包并导入对 Amazon.Lambda.Serialization.Json 命名空间的引用。

public class Sample
{
    [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
    public object Test()
    {
        return new { FirstName = "William Smith" };
    }
}

[1]: Github link

关于c# - 从 C# 中的 AWS Lambda 函数返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43904822/

相关文章:

c# - 从 Azure 数据湖下载文件

c# - 在后面的代码中赋予 <a> 样式

python - Python 中基于类的 AWS lambda

python - 如何在Chalice(AWS Lambda/API Gateway)应用程序中访问原始查询字符串(或完整URL)?

c# - 在 ASP.NET MVC 应用程序中将逻辑放在哪里,以便每个页面请求始终触发(仅一次)?

c# - 克隆一个对象,同时从扩展方法维护派生类型

python - AWS Lambda 函数的快速数据访问

AWS lambda 中的 Java 8 并发?

node.js - 无效的 ELF header - Argon2 包

c# - 防止 MDX 注入(inject)攻击