简体   繁体   English

C#中的Azure函数内容Webhook错误

[英]Azure Function Contentful Webhook Error in C#

I'm having problems trying to obtain the http response from the contentful webhooks. 我在尝试从内容丰富的Webhooks中获取http响应时遇到问题。 I keep getting this error: 我不断收到此错误:

"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" “ WebHook请求包含无效的JSON:'没有MediaTypeFormatter可用于从媒体类型为'application / vnd.contentful.management.v1 + json的内容中读取'JToken'类型的对象”

This is my function code: 这是我的功能代码:

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

The problem is that ReadAsAsync is trying to use the default media formatters which by default only allows application/json . 问题是ReadAsAsync尝试使用默认的媒体格式化程序,默认情况下仅允许application/json

You could of course just register to use the json formatter for the contentful content type as well, but I'd suggest suggest using NewtonSoft.Json and doing something like this. 当然,您也可以注册以将json格式化程序用于内容类型,但是我建议您建议使用NewtonSoft.Json并执行类似的操作。

string json = await req.Content.ReadAsStringAsync();
dynamic data = JsonConvert.DeserializeObject(json);

Here is a complete function that works with a webhook from Contentful: 这是与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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM