WCF自定义错误处理中的响应类型

时间:2018-11-22 07:11:53

标签: c# rest wcf response ierrorhandler

我正在研究使用WCF App开发的休息服务。服务可以同时使用xml和json格式。而且我必须处理错误,因此我开发了一个从IErrorHandler派生的ErrorHandler。

    public class ErrorHandler : IErrorHandler
{
    public bool HandleError(Exception error)
    {
        return true;
    }

    public void ProvideFault(Exception exception, MessageVersion messageVersion, ref Message message)
    {
        CommonManager.Log($"Message:{exception.Message}, Stack Trace:{exception.StackTrace}");
        var response = CommonManager.CreateResponse(exception.Message);
        message = Message.CreateMessage(messageVersion, string.Empty, response, new DataContractJsonSerializer(typeof(ContainerModel<object>)));
        var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
        message.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
        var rmp = new HttpResponseMessageProperty();
        message.Properties.Add(HttpResponseMessageProperty.Name, rmp);
        rmp.StatusCode = System.Net.HttpStatusCode.OK;
    }
}

在下面您可以看到XML响应。根属性的类型是“对象”。

   <s:Body>
  <root type="object">
     <Data type="null"/>
     <IsSucceeded type="boolean">false</IsSucceeded>
     <Message>The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:data. The InnerException message was 'There was an error deserializing the object of type CosmosXIAMWebServices.Models.UserModel. The value 'asd' cannot be parsed as the type 'Int32'.'.  Please see InnerException for more details.</Message>
  </root>

通常,如果请求成功。根属性类型为“ AddOrUpdateUserResponse”;

   <s:Body>
  <AddOrUpdateUserResponse xmlns="http://tempuri.org/">
     <AddOrUpdateUserResult xmlns:a="http://schemas.datacontract.org/2004/07/CosmosXIAMWebServices.Models" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <a:Data>
           xx
        </a:Data>
        <a:IsSucceeded>false</a:IsSucceeded>
        <a:Message>Username is already exist with that user code</a:Message>
     </AddOrUpdateUserResult>
  </AddOrUpdateUserResponse>

在错误和成功期间,我需要响应类型相同。

谢谢。

0 个答案:

没有答案