c# - Azure Functions V2 将 HttpRequest 反序列化为对象

标签 c# azure-functions

我很惊讶我找不到这个问题的答案,但我有一个 Azure 函数(HTTP 触发器)我只是想将内容反序列化为一个对象。以前使用 V1 我能够做到这一点,

函数 V1

[FunctionName("RequestFunction")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
    // Successful deserialization of the content
    var accountEvent = await req.Content.ReadAsAsync<AccountEventDTO>();

    // Rest of the function...
}

但现在有了 V2,它看起来更像是这样,

函数 V2

[FunctionName("RequestFunction")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, ILogger log)
{
    // Content doesn't exist on HttpRequest anymore so this line doesn't compile
    var accountEvent = await req.Content.ReadAsAsync<AccountEventDTO>();

    // Rest of the function...
}

我可以让正文从 HttpRequest 对象访问流,但不确定如何将其转换为预期的对象。有什么想法吗?

最佳答案

API 发生了一些变化。如您所见,Content 不再存在。但是,您仍然可以通过使用包含在 Microsoft.Azure.WebJobs.Extensions.Http 命名空间(应该已经作为依赖项包含在内)中的扩展方法来获得相同的功能:

string json = await req.ReadAsStringAsync();

可以查看这个扩展方法的来源here

然后你会使用 Json.NET 反序列化(Json.NET 也已经是一个依赖)

var someModel = JsonConvert.DeserializeObject<SomeModel>(json);

关于c# - Azure Functions V2 将 HttpRequest 反序列化为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52726080/

相关文章:

c# - 如何编译特定语言版本的C#

node.js - 您可以根据事件中心消息 header 属性有条件地触发 azure 函数吗?

c# - Azure 函数绑定(bind)与手动实例化类

azure - Azure Durable Functions 是否支持 .NET 6 和 Azure Functions 版本 4?

azure - 使用 Azure CLI 部署 .zip Function App 时权限被拒绝

c# - 长度为 1 的字符串比较给出的结果与字符比较不同……为什么?

c# - 表达式使用参数调用构造函数并设置其值

c# - Windows 中文件的全局唯一 ID

c# - 最大化时从顶部拖动自定义窗口标题栏不起作用

Azure 数据工厂管道 - 将单值源查询输出存储为变量,然后在复制数据事件中使用