I have a WCF web service (.svc) like this:
Web Service
Interface
namespace Interfaces
{
[ServiceContract]
public interface IGeneral
{
[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
List<Person> GetPerson(long personID, DateTime startDate);
}
}
Class
[ScriptService]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class GeneralService : Interfaces.IGeneral
{
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
[WebMethod]
public List<Person> GetPerson(long personID, DateTime startDate)
{
List<Person> people= new List<Person>();
people.Add(new Person()
{
PersonID= 2,
StartDate= new DateTime(),
});
return people;
}
}
Person
namespace Models
{
[DataContract]
public class Person
{
[DataMember]
public long PersonID{ get; set; }
[DataMember]
public DateTime StartDate{ get; set; }
}
}
I'm expecting this to come back with Json but it just gives an error. I should be able to test this from the browser being a GET just like this (as you can see I donøt use the parameters in input so there should be no problem not passing them in):
http://localhost:2880/GeneralService/GetPerson
the way I call it is this:
Client Call
var request = {
personID: 3,
startDate: new Date(),
};
ajaxService = (function () {
var ajaxGetJson = function (method, request, callback, service) {
$.ajax({
url: getSvcUrl(service, method),
type: "GET",
data: request,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result, statusMsg, status)
{
callback(result, statusMsg, status, request)
},
error: ServiceFailed // When Service call fails
})
}
return {
ajaxGetJson: ajaxGetJson,
};
})();
ajaxService.ajaxGetJson("GetPerson", request, ModelMetricsMapper, "http://localhost:2880/GeneralService/");
UPDATE
I have a bit more info, it seems that it works if I change the class that I'm returning. I explain: if my class is just a simple class with primitives inside it does NOT work, BUT if I add a wrapper class around each primitive... it suddenly works. It seems that the response Class needs to be 2 levels nested at least.
Here is the new class that works:
Works
[DataContract]
public class Person {
[DataMember]
public IdClass PersonID{ get; set; }
[DataMember]
public DateClass StartDate{ get; set; }
}
WHY?
I will answer this question with a way I found that works using javascriptSerializer.Serialize and retuning a Strem back to the client, but I would really like a way to do it returng a Person Object like Dave Ward says in this post: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/ but I just canøt make it work.
What am I doing wrong?
Thanks for any help.