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



我在函数应用中具有以下代码

using System.Net;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
   var data = await req.Content.ReadAsAsync<PostData>();
   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'.

如何将功能设置为使用正确的媒体类型?

[更新]

如果我将代码更改为

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

我可以看到以

开始记录的jsoncontent文本
ToCountry=AU&ToState=&SmsMessageSid=SM8cac6c6a851  etc

但是我不清楚如何提取所需的数据。

我尝试添加

 dynamic results = JsonConvert.DeserializeObject<dynamic>(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<object> 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)

对于应用程序/x-www-form-urlenCoded,发送到服务器的HTTP消息的主体本质上是一个巨大的查询字符串 - 名称/值对由ampersand(&amp;)分开,名称分开来自等于符号(=)的值。一个例子是:

MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

我们可以从另一个so线程中获取有关应用程序/x-www-form-urlencodod的更多信息。

当前,并非所有的ASP.NET Webhook接收器均已完全处理。我还找到了一个smilar so线程。Azure功能可以支持3种类型的Webhooks:通用JSON,GITHUB,SLACK 。但是我们可以通过逻辑来处理它。您可以尝试使用以下代码来获取字典中的键值。

 Dictionary<string, string> myDictionary = new Dictionary<string, string>();
 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}"); 

相关内容

最新更新