我很惊讶我找不到这个问题的答案,但我有一个 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/