WCF service, Json serialization and errors finding
L开发者_Go百科et's say that I have simple WCF service:
[ServiceContract]
public interface ITestService
{
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
object Operation();
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class TestService : ITestService
{
public object Operation()
{
return /*some object*/
}
}
and an aspx page that makes the ajax call to this service and uses the returned object, here is the ajax call:
$.ajax({
type: "POST",
url: "TestService.svc/Operation",
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: true,
success: function (msg) {
var res = msg.OperationResult;
},
error: function (xhr, msg, thrown) {
var error = xhr;
}
});
If Operation() returns the simple object like string or number, then msg.OperationResult returns this object, no error is thrown, all works fine. However, if I try to return the complicated object that has the public and internal properties of public and internal reference types, then msg.OperationResult passed in success callback is undefined. error callback is not raised. It seems that WCF is trying to serialize the complicated object, faces the error and just returns null instead of throwing the exception. The question is - how I can handle this type of errors? Which serializer is used by WCF internally? Is it DataContractJsonSerializer?
- yes, it's the DataContractJsonSerializer which is used.
- WCF will only serialize types which it knows about. You declared the return type as
object
, so it will only be able to return either instances of System.Object, or the primitive types which are always known by WCF (such as numbers, strings, DateTime, etc). If you need to return a complex type, you need to declare it as a known type in the contract, as shown below.
The contract with a declaration for the known type. For more information, see the documentation for the ServiceKnownType attribute.
[ServiceContract]
public interface ITestService {
[OperationContract]
[ServiceKnownType(typeof(MyComplexType))]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
object Operation();
}
精彩评论