C# 中的 Azure Function Contentful Webhook 错误

Azure Function Contentful Webhook Error in C#

我在尝试从 contentful webhooks 获取 http 响应时遇到问题。我不断收到此错误:

"The WebHook request contained invalid JSON: 'No MediaTypeFormatter is available to read an object of type 'JToken' from content with media type 'application/vnd.contentful.management.v1+json"

这是我的函数代码:

#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}!"
  });
}

问题是 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);
}