[英]How to receive json post data in a Webhook
我们正在使用第三方api kraken.io优化我们的图像。
优化图像的结果发布在Webhook
。
在他们的API文档它规定:优化过海妖会后POST
消息到callback_url
在一个你的要求指定的JSON
格式application/json
。
我使用ngrok允许远程webhooks
将数据发送到自己的计算机,使用此文章。
结果发布到回调URL:
HTTP/1.1 200 OK
{
"id": "18fede37617a787649c3f60b9f1f280d",
"success": true,
"file_name": "header.jpg",
"original_size": 324520,
"kraked_size": 165358,
"saved_bytes": 159162,
"kraked_url": "http://dl.kraken.io/18/fe/de/37617a787649c3f60b9f1f280d/header.jpg"
}
类到地图
public class KrakenOptimizedResults
{
public string id { get; set; }
public bool success { get; set; }
public string file_name { get; set; }
public int original_size { get; set; }
public int kraked_size { get; set; }
public int saved_bytes { get; set; }
public string kraked_url { get; set; }
}
行动方法
[HttpPost]
public ActionResult OptimizedWebHook()
{
Request.InputStream.Position = 0;
string jsonString = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
KrakenOptimizedResults obj = new JavaScriptSerializer().Deserialize<KrakenOptimizedResults>
(jsonString);
return Json(obj);
}
但是,当我在Html Visualizer中debug
收到的jsonString
,它看起来像key
和value
对,而不是Json格式。
收到的结果不是Json格式的:
file_name=header.jpeg&original_size=118066&kraked_size=102459&saved_bytes=15607
我猜收到的数据content-type:
是content-type:
application/x-www-form-urlencoded
。
为什么我收到key
和value
对而不是Json格式? 如何在asp.net mvc中反序列化Json数据?
https://kraken.io的共同创始人。
我的文档中有一个明显的遗漏,我将在今天修复。 要取回JSON,您需要在请求中设置一个"json": true
标志。 省略该标志或将"json": false
设置为"json": false
将返回URLEncoded。 cURL请求示例:
curl http://api.kraken.io/v1/upload -X POST --form data='{"auth":{"api_key":"YOUR_KEY", "api_secret":"YOUR_SECRET"}, "wait": true, "lossy": true, "callback_url": "http://requestb.in/wbhi63wb", "json": true}' --form upload=@test.jpg
抱歉给你带来不便 :-(
第1步:创建一个aspx页面。 该页面必须能够接受HTTP POST请求。 步骤2:添加此代码以获取HTTP POST数据文件:default.aspx.cs文件:default.aspx.cs
var reader = new StreamReader(Request.InputStream);
var json = reader.ReadToEnd();
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
ostrm = new FileStream(@"C:\logfile4webhook.txt", FileMode.Append, FileAccess.Write);
writer = new StreamWriter(ostrm);
Console.SetOut(writer);
Console.Write(DateTime.Now + " ");
Console.WriteLine(json.ToString() + " ");
Console.SetOut(oldOut);
writer.Close();
ostrm.Close();
第3步:创建Webhook。 此代码可以链接到click事件上的按钮。File:default.aspx.cs
AuthenticationDetails auth = new ApiKeyAuthenticationDetails("your api key");
string listID = "";
listID = "your list id";
List list = new List(auth, listID);
List<string> events = new List<string>();
events.Add("Update");
string postback = list.CreateWebhook(events, "URL", "json");
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
ostrm = new FileStream(@"C:\logfile4webhook.txt", FileMode.Append, FileAccess.Write);
writer = new StreamWriter(ostrm);
Console.SetOut(writer);
Console.Write(DateTime.Now + " ");
Console.WriteLine(postback + " ");
Console.SetOut(oldOut);
writer.Close();
ostrm.Close();
步骤4:激活webhook。 从文本文件中复制该webhook ID并将其粘贴到下面的代码中。 文件:default.aspx.cs
AuthenticationDetails auth = new ApiKeyAuthenticationDetails("your api key");
string listID = "";
listID = "your list id";
List list = new List(auth, listID);
list.ActivateWebhook("webhook id");
步骤5:测试weebhook.File:default.aspx.cs
AuthenticationDetails auth = new ApiKeyAuthenticationDetails("your api key");
string listID = "";
listID = "your list id";
List list = new List(auth, listID);
string postback = list.TestWebhook("webhook id").ToString();
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
ostrm = new FileStream(@"C:\logfile4webhook.txt", FileMode.Append, FileAccess.Write);
writer = new StreamWriter(ostrm);
Console.SetOut(writer);
Console.Write(DateTime.Now + " ");
Console.WriteLine(postback + " ");
Console.SetOut(oldOut);
writer.Close();
ostrm.Close();
步骤6:反序列化JSON对象的主体。 我们需要基于JSON数据创建类结构。 我将示例json放在此处,并创建了所需的类
public class CustomField
{
public string Key { get; set; }
public string Value { get; set; }
}
public class Event
{
public List<CustomField> CustomFields { get; set; }
public string Date { get; set; }
public string EmailAddress { get; set; }
public string Name { get; set; }
public string SignupIPAddress { get; set; }
public string Type { get; set; }
}
public class RootObject
{
public List<Event> Events { get; set; }
public string ListID { get; set; }
}
创建好类后,请在第二步之后附加代码
var json = reader.ReadToEnd();
反序列化和解析json。
RootObject myClass = JsonConvert.DeserializeObject(json);
if (myClass != null)
{
List<Event> t = myClass.Events;
string old_email = "", new_email = "";
old_email = t[0].OldEmailAddress;
new_email = t[0].EmailAddress;
//now you can do your logic with old_email and new_email
}
我能够使用此和这篇文章将查询字符串Key
和Value
对转换为Json
格式,将Dictionary
转换为Json
会有一些延迟,因此,如果有更好的答案,那么请发表和建议,以下是我的解决方案。
行动方法
[HttpPost]
public ActionResult OptimizedWebHook()
{
Request.InputStream.Position = 0;
string data = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
var dict = HttpUtility.ParseQueryString(data);
var json = new JavaScriptSerializer().Serialize(dict.AllKeys.ToDictionary(k => k, k =>
dict[k]));
KrakenOptimizedResults obj = new JavaScriptSerializer().Deserialize<KrakenOptimizedResults>
(json);
return Json(obj);
}
从kraken API接收JSON格式的优化结果。
如@ karim79所述,要取回JSON,您需要在请求中设置一个“ json”:true标志。
由于Kraken .Net/C#
SDK没有设置“ json”的选项:true,因此我必须扩展其基类。
扩展基类:
public class OptimizeRequestBaseExtended : OptimizeRequestBase,
IOptimizeUploadRequest, IRequest
{
public OptimizeRequestBaseExtended(Uri callbackUrl)
{
CallbackUrl = callbackUrl;
}
[JsonProperty("callback_url")]
public Uri CallbackUrl { get; set; }
[JsonProperty("json")]
public bool JsonFormat { get; set; }
}
请求Kraken API:
var callbackUrl = new Uri("http://localhost:0000/Home/OptimizedWebHook");
OptimizeRequestBaseExtended settings = new OptimizeRequestBaseExtended(callbackUrl);
settings.Lossy = true;
settings.JsonFormat = true;
var response = client.Optimize(image: image, filename: filename, optimizeRequest: settings);
行动方法
[HttpPost]
public ActionResult OptimizedWebHook()
{
Request.InputStream.Position = 0;
string jsonString = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
KrakenOptimizedResults obj = JsonConvert.DeserializeObject<KrakenOptimizedResults>
(jsonString);
return Json(obj);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.