如何设置function应用程序以从媒体类型’application / x-www-form-urlencoded’中提取数据

我的function应用程序中有以下代码

using System.Net; public static async Task Run(HttpRequestMessage req, TraceWriter log) { var data = await req.Content.ReadAsAsync(); var sid = data.sid; log.Info($"sid ={sid}"); return req.CreateResponse(HttpStatusCode.OK, $"Current Time : {DateTime.Now}"); } public class PostData { public string sid { get; set; } } 

错误消息是

 No MediaTypeFormatter is available to read an object of type 'PostData' from content with media type 'application/x-www-form-urlencoded'. 

如何设置该function以使用正确的介质类型?

[更新]

如果我将代码更改为

 var content = req.Content; var jsonContent = await content.ReadAsStringAsync(); log.Info(jsonContent); 

我可以看到开始记录的jsonContent文本

 ToCountry=AU&ToState=&SmsMessageSid=SM8cac6c6a851 etc 

但我不知道如何提取我需要的数据。

我尝试添加

  dynamic results = JsonConvert.DeserializeObject(jsonContent); 

 using Newtonsoft.Json; 

但是这会导致脚本编译错误

[更新]研究“集成”选项卡上的示例代码

GitHub WebHook函数的示例C#代码

 #r "Newtonsoft.Json" using System; using System.Net; using System.Threading.Tasks; using Newtonsoft.Json; public static async Task Run(HttpRequestMessage req, TraceWriter log) { string jsonContent = await req.Content.ReadAsStringAsync(); log.Info("Hi 1"); // does log dynamic data = JsonConvert.DeserializeObject(jsonContent); log.Info("Hi 2"); // does not log return req.CreateResponse(HttpStatusCode.OK, $"Current Time : {DateTime.Now}" }); } 

这会产生错误

 System.AggregateException : One or more errors occurred. ---> Unexpected character encountered while parsing value: T. Path '', line 0, position 0. at Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.GetTaskResult(Task task) 

对于application / x-www-form-urlencoded,发送到服务器的HTTP消息的主体实际上是一个巨大的查询字符串 – 名称/值对由&符号(&)分隔,名称与值分隔开来。等于符号(=)。 一个例子是:

 MyVariableOne=ValueOne&MyVariableTwo=ValueTwo 

我们可以从另一个SO线程获得有关application / x-www-form-urlencoded的更多信息。

目前,并非所有各种ASP.NET WebHook接收器都在函数中完全处理。 我也找到了一个微笑的SO线程 。 Azure Functions可以支持3种类型的webhook: Generic JSON,GitHub,Slack 。 但我们可以用我们的逻辑处理它。 您可以尝试使用以下代码来获取Dictionary中的键值。

  Dictionary myDictionary = new Dictionary(); if (req.Content.Headers.ContentType.ToString().ToLower().Equals("application/x-www-form-urlencoded")) { var body = req.Content.ReadAsStringAsync().Result; var array = body.Split('&'); foreach (var item in array) { var keyvalue = item.Split('='); myDictionary.Add(keyvalue[0],keyvalue[1]); } } var sid = myDictionary["SmsMessageSid"]; log.Info($"sid ={sid}"); return req.CreateResponse(HttpStatusCode.OK, $"Current Time : {DateTime.Now}");