WCF JSON服务在Fault上返回XML

Ant*_*ton 11 wcf json

我正在运行一个ServiceHost来测试我的一个服务,所有工作正常,直到我抛出一个FaultException - 我得到XML而不是JSON

我的服务合同 - 可爱

   /// <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);
Run Code Online (Sandbox Code Playgroud)

主机设置 - scumum 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();
Run Code Online (Sandbox Code Playgroud)

这是电话 - 肚子疼

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

text var包含正确的错误,但序列化为Xml我在这里做错了什么?

Ant*_*ton 3

答案是实现 IErrorHandler 和支持行为

我发现了 iainjmitchell 写的这篇很棒的帖子

http://iainjmitchell.com/blog/?p=142

  • 难点在于如何为 SOAP 客户端抛出FaultException,为 REST 客户端抛出 WebHttpException...我还没有弄清楚这一点。 (2认同)