WYSIWYG

http://kufli.blogspot.com
http://github.com/karthik20522

Thursday, November 29, 2012

HttpWebRequest - 500 Internal Server Error - Faulty JSON



So while making a web request from a C# application and if you end up hitting a 500 Internal Server error its usually because of the following or atleast this is what most google would talk about:

As a note, Internal Server Error is on the server side, The server crapped out on something
Most common issues that's not related to your actual code:
  • Maybe Invalid authentication or invalid credentials
  • Maybe invalid contenttype being passed
  • Maybe wrong request method (GET instead of POST or vice-versa)
  • Maybe invalid content length being posted
  • Or even maybe because of some proxy issue
But I came across something very strange recently while doing a Http POST from a c# WebPI application to a REST based WCF service. So it seems like the Newtonsoft JSON.NET that come's along with WebAPI (NuGet) is serializing the DateTime object to JSON a bit differently. The old JSON.NET library converted DateTime value into Ticks while the new JSON.NET library is coverting it to a string. Following is an example of old and new JSON.NET library:

New JSON.NET Library: Old JSON.NET Library: So it seems that WCF is unable to deserialize the new DateTime format and fails during deserialization of input as the DateTime types are different. One solution to this problem is to serialize the object to JSON using the JavascriptSerializer (System.Web.Script.Serialization namespace). Example code:

Labels: , , , ,