I’ve been playing around with creating a REST based WCF service sending and receiving json data. I’m able to get most things working, but this last piece has really stumped me.
I’m sending in a complex data type to my service. I’m sending data, but it seems as if my class isn’t being instantiated.
Class declaration (in a separate class file):
public class WhereItsAt
{
public float Latitude { get; set; }
public float Longitude { get; set; }
public string Category { get; set; }
public string SearchTerms { get; set; }
public float Distance { get; set; }
}
[WebInvoke(Method = "POST", UriTemplate = "/New", RequestFormat = WebMessageFormat.Json)]
public string Create(WhereItsAt newstuff)
{
return string.Format("Success: {0} <Should show search terms here>", newstuff.SearchTerms);
}
The problem is that newstuff.SearchTerms (OK, all of newstuff) is null or 0.
If I modify my class:
public class WhereItsAt
{
public float Latitude { get; set; }
public float Longitude { get; set; }
public string Category { get; set; }
public string SearchTerms { get{return "hello"}; set; }
public float Distance { get; set; }
}
it returns data.
I’m calling with Fiddler:
POST http://127.0.0.1:8835/testing/New HTTP/1.1
User-Agent: Fiddler
Host: 127.0.0.1:8835
Content-Length: 122
Content-Type: application/json; charset=utf-8
[{“Latitude”:43.34,”Longitude”:45.234,”Category”:”Not set yet”,”SearchTerms”:”Downtown”,”Distance”:12.234}]
It looks to me as if my class is not being instantiated. I’ve created some dummy code in the set
{set{int i = 1;};
but if I create a breakpoint in the set, it is never called.
What am I doing wrong?
You need to add the DataContract and DataMember attributes to your data model…
see http://msdn.microsoft.com/en-us/library/ms733127.aspx