I was working on a side project when i came across a rather interesting way to get post data from an HTTP post that i thought i’d share.
first i had an HTTP Post via angularJS
convert: function (prefix, suffix, delimiter) { var data = { "prefix": prefix, "suffix": suffix, "delimiter": delimiter }; return $http.post("manager/convert.json", data); }
Initially i tried to access the Request.Form but for some reason it wasn’t being populated. So that lead me to get a little bit creative. Using a streamreader to get the input stream from the HTTPContext we’re able to use JsonNet to deserialize the json into a dynamic c# object
/// <summary> /// gets data from post request /// </summary> /// <param name="context"></param> /// <returns>dynamic object containing post javascript object</returns> public static dynamic GetPostData(HttpContextBase context) { using (StreamReader sr = new StreamReader(context.Request.InputStream)) { return JsonConvert.DeserializeObject<ExpandoObject>(sr.ReadToEnd()); } }
Which can then be used like this:
private object Convert(HttpContextBase context) { var data = GetPostData(context); var converter = new Converter(data.prefix, data.suffix, data.delimiter); return converter.Convert(); }
The flexibility of being contract-less in the exchange is pretty freeing and refreshing. However i do want to point out that this is much less safe than creating a strict model for the exchange of information. That being said i see nothing wrong with using this approach for less critical subsystems.