我正在尝试计算如何将此curl片段转换为.net HttpClient作为Post请求。从下面的图像中获取服务器返回的500错误。
这是curl命令,用于ConvertKit创建webhook。
curl -X POST https://api.convertkit.com/v3/automations/hooks
-H 'Content-Type: application/json'\
-d '{ "api_secret": "<your_secret_api_key>",\
"target_url": "http://example.com/incoming",\
"event": { "name": "subscriber.subscriber_activate" } }'
参考链接:http://developers.convertkit.com/#webhooks
这是我的.net代码段:
private static async Task<HttpResponseMessage> PostConverkitCreateWebhookSubscription()
{
var client = new HttpClient {BaseAddress = new Uri("https://api.convertkit.com ") };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
dynamic event1 = new ExpandoObject();
event1.name = "subscriber.subscriber_activate";
var customEvent = JsonConvert.SerializeObject(event1);
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("api_secret", "<your_secret_api_key>"),
new KeyValuePair<string, string>("target_url","http://example.com/incoming"),
new KeyValuePair<string, string>("event", customEvent)
};
var request = new HttpRequestMessage(HttpMethod.Post, "/v3/automations/hooks")
{
Content = new FormUrlEncodedContent(keyValues)
};
return await client.SendAsync(request);
}
获取错误500,所以我可能会对他们的服务器造成严重破坏。
可能是可能事件的JSON对象......不确定..需要帮助
答案 0 :(得分:2)
FormUrlEncodedContent
对类似于查询字符串的键值对进行编码。您基本上告诉它发送URL编码的键值对,其中最后一个值是JSON编码的。所以你的请求主体看起来像这样:
api_secret=<your_secret_api_key>&target_url=http://example.com/incoming&event={"name":"subscriber.subscriber_activate"}
但是API期望整个有效负载都是JSON编码的。这个修改过的版本可以解决这个问题:
var data = new
{
api_secret = "<your_secret_api_key>",
target_url = "http://example.com/incoming",
@event = new
{
name = "subscriber.subscriber_activate"
}
};
var json = JsonConvert.SerializeObject(data); // json-encode everything, not just event
var client = new HttpClient { BaseAddress = new Uri("https://api.convertkit.com ") };
var content = new StringContent(json, Encoding.UTF8, "application/json");
return await client.PostAsync("/v3/automations/hooks", content);
作为旁注,event
是C#中的保留字; @event
是如何将其转义为将其用作属性名称。