WCF JSON Service returns XML on Fault
Posted
by
Anthony Johnston
on Stack Overflow
See other posts from Stack Overflow
or by Anthony Johnston
Published on 2011-06-22T13:29:45Z
Indexed on
2011/06/26
8:22 UTC
Read the original article
Hit count: 329
I am running a ServiceHost to test one of my services and all works fine until I throw a FaultException - bang I get XML not JSON
my service contract - lovely
/// <summary>
/// <para>Get category by id</para>
/// </summary>
[OperationContract(AsyncPattern = true)]
[FaultContract(typeof(CategoryNotFound))]
[FaultContract(typeof(UnexpectedExceptionDetail))]
IAsyncResult BeginCategoryById(
CategoryByIdRequest request,
AsyncCallback callback, object state);
CategoryByIdResponse EndCategoryById(IAsyncResult result);
Host Set-up - scrummy yum
var host = new ServiceHost(serviceType, new Uri(serviceUrl));
host.AddServiceEndpoint(
serviceContract,
new WebHttpBinding(), "")
.Behaviors.Add(
new WebHttpBehavior
{
DefaultBodyStyle = WebMessageBodyStyle.Bare,
DefaultOutgoingResponseFormat = WebMessageFormat.Json,
FaultExceptionEnabled = true
});
host.Open();
Here's the call - oo belly ache
var request = WebRequest.Create(serviceUrl + "/" + serviceName);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = 0;
try
{
// receive response
using (var response = request.GetResponse())
{
var responseStream = response.GetResponseStream();
// convert back into referenced object for verification
var deserialiser = new DataContractJsonSerializer(typeof (TResponseData));
return (TResponseData) deserialiser.ReadObject(responseStream);
}
}
catch (WebException wex)
{
var response = wex.Response;
using (var responseStream = response.GetResponseStream())
{
// convert back into fault
//var deserialiser = new DataContractJsonSerializer(typeof(FaultException<CategoryNotFound>));
//var fex = (FaultException<CategoryNotFound>)deserialiser.ReadObject(responseStream);
var text = new StreamReader(responseStream).ReadToEnd();
var fex = new Exception(text, wex);
Logger.Error(fex);
throw fex;
}
}
the text var contains the correct fault, but serialized as Xml What have I done wrong here?
© Stack Overflow or respective owner