Search code examples
jsonasp.net-mvcasp.net-mvc-4json.netkraken-image-optimizer

How to receive json post data in a Webhook


We are using 3rd party api kraken.io to optimize our images.

The results of optimized image is posted in a Webhook.

In their api document it states: After the optimization is over Kraken will POST a message to the callback_url specified in your request in a JSON format application/json.

I am using ngrok to allow remote webhooks to send data to my development machine, using this article.

Results posted to the Callback 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"
}

Class to Map

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; }
}

Action Method

[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);

 }     

But When I debug the received jsonString in Html Visualizer it looks like key and value pairs instead of Json format.

Received Results not Json Formatted:

file_name=header.jpeg&original_size=118066&kraked_size=102459&saved_bytes=15607

I guess the received data content-type: is application/x-www-form-urlencoded.

Why i am receiving key and value pairs instead of Json format ? how can I deserialize Json data in asp.net mvc ?


Solution

  • Co-founder of https://kraken.io here.

    There is a glaring omission in our documentation which I will fix today. To get JSON back, you need to set a "json": true flag in the request. Omitting that flag or setting "json": false will return URLEncoded. Example cURL request:

    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 [email protected]
    

    Sorry for the inconvenience :-(