我在尝试从内容丰富的webhook中获取http响应时遇到问题。我一直收到这个错误:
“WebHook请求包含无效的JSON:'没有MediaTypeFormatter可用于从媒体类型为'application / vnd.contentful.management.v1 + json'的内容中读取'JToken'类型的对象”
这是我的功能代码:
#r "Newtonsoft.Json"
using System;
using System.Net;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
using System.Web.Http;
public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
@json(body('formdataAction'));
log.Info($"wjat");
// req.Headers.ContentType = new MediaTypeHeaderValue("application/json");
log.Info($"Webhook was triggered!");
string jsonContent = await req.Content.ReadAsStringAsync();
// BodyParser.Of(BodyParser.TolerantJson.class);
dynamic data = JsonConvert.DeserializeObject(jsonContent);
log.Info(data.sys);
if (data.first == null || data.last == null)
{
return req.CreateResponse(HttpStatusCode.BadRequest, new
{
error = "Please pass first/last properties in the input object"
});
}
return req.CreateResponse(HttpStatusCode.OK, new
{
greeting = $"Hello {data.first} {data.last}!"
});
}
答案 0 :(得分:0)
问题是ReadAsAsync
正在尝试使用默认的媒体格式化程序,默认情况下只允许application/json
。
你当然可以注册使用json格式化程序来获取内容丰富的内容类型,但我建议使用NewtonSoft.Json并做类似的事情。
string json = await req.Content.ReadAsStringAsync();
dynamic data = JsonConvert.DeserializeObject(json);
这是一个完整的功能,可与Contentful:
中的webhook一起使用#r "Newtonsoft.Json"
using System.Net;
using Newtonsoft.Json;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req,
TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
// Get request body
string json = await req.Content.ReadAsStringAsync();
log.Info($"Read json: {json}");
dynamic data = JsonConvert.DeserializeObject(json);
string deserialized = data?.ToString();
return req.CreateResponse(HttpStatusCode.OK, deserialized);
}