3

我有一个配置为使用 json 的 WCF 4 REST 服务。我想捕获异常并返回 400 的 HTTP 状态代码,并将异常消息作为 json 对象。我已经按照网络上的示例来实现我自己的 IErrorHandler 和 IService 接口来执行此操作。

例如:

http://zamd.net/2008/07/08/error-handling-with-webhttpbinding-for-ajaxjson/

从启用 AJAX 的 WCF 服务返回错误详细信息

http://social.msdn.microsoft.com/Forums/en/wcf/thread/fb906fa1-8ce9-412e-a16a-5d4a2a0c2ac5

但是,就像在这篇文章中一样

当 WCF 方法抛出异常时,使用空响应调用 jQuery 成功回调

我得到一个 202 Accepted 响应,没有数据,这是由于我尝试创建错误时的序列化错误。这是从我的服务中记录的,如下所示:

2012-01-31 00:37:19,229 [8] DEBUG JsonWebScriptServiceHostFactory: creating service host
2012-01-31 00:37:19,292 [8] DEBUG JsonErrorHandler.ApplyDispatchBehavior: adding error handler
2012-01-31 00:43:06,995 [10] DEBUG ForemanSvc.GetSessionID
2012-01-31 00:43:39,292 [10] DEBUG ForemanSvc.GetProjects
2012-01-31 00:43:39,448 [10] DEBUG JsonErrorHandler.ProvideFault: creating fault
2012-01-31 00:43:39,635 [10] ERROR ForemanSvc exeption
Type: System.ServiceModel.CommunicationException
Message: Server returned an invalid SOAP Fault.  Please see InnerException for more details.
Source: System.ServiceModel
StackTrace:    
at System.ServiceModel.Channels.MessageFault.CreateFault(Message message, Int32 maxBufferSize)
at System.ServiceModel.Description.WebScriptEnablingBehavior.JsonErrorHandler.ProvideFault(Exception error, MessageVersion version, Message& fault)
at System.ServiceModel.Dispatcher.ErrorBehavior.ProvideFault(Exception e, FaultConverter faultConverter, ErrorHandlerFaultInfo& faultInfo)
at System.ServiceModel.Dispatcher.ErrorBehavior.ProvideMessageFaultCore(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage8(MessageRpc& rpc)
Type: System.Xml.XmlException
Message: Start element 'Fault' from namespace 'http://schemas.microsoft.com/ws/2005/05/envelope/none' expected. Found element 'root' from namespace ''.
Source: System.Runtime.Serialization
StackTrace:    
at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
at System.Xml.XmlExceptionHelper.ThrowStartElementExpected(XmlDictionaryReader reader, String localName, String ns)
at System.Xml.XmlDictionaryReader.ReadStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
at System.ServiceModel.Channels.ReceivedFault.CreateFault12Driver(XmlDictionaryReader reader, Int32 maxBufferSize, EnvelopeVersion version)
at System.ServiceModel.Channels.MessageFault.CreateFault(Message message, Int32 maxBufferSize)

从那篇文章中不清楚如何解决它。我已经尝试了各种方法——使用属性、使用端点行为、尝试没有 json 格式或返回额外信息的简单 CreateMessage——似乎没有任何效果。任何人都可以帮忙吗?

这是一些代码片段 - 错误处理程序

public class JsonErrorHandler : IServiceBehavior, IErrorHandler
{
  private static readonly ILog log =
    LogManager.GetLogger(System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType);


  public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
  {
    //Dont do anything
  }

  public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,
                                 Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
  {
    //dont do anything
  }

  public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
  {
    log.IfDebug("JsonErrorHandler.ApplyDispatchBehavior: adding error handler");
    foreach (ChannelDispatcherBase dispatcherBase in serviceHostBase.ChannelDispatchers)
    {
      ChannelDispatcher channelDispatcher = dispatcherBase as ChannelDispatcher; 
      if (channelDispatcher != null)
      {
        channelDispatcher.ErrorHandlers.Add(this);
      } 
    }
  }


  public bool HandleError(Exception error)
  {
    log.IfError("ForemanSvc exeption", error);
    //Tell the system that we handle all errors here.
    return true;
  }

  public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
  {
    log.IfDebug("JsonErrorHandler.ProvideFault: creating fault");

    JsonError msErrObject =
    new JsonError
    {
      Message = error.Message,
      Source = error.Source,
      Detail = error.InnerException != null ? error.InnerException.Message : null
    };


    //The fault to be returned
    fault = Message.CreateMessage(version, "", msErrObject, new DataContractJsonSerializer(msErrObject.GetType()));

    // tell WCF to use JSON encoding rather than default XML
    WebBodyFormatMessageProperty wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

    // Add the formatter to the fault
    fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

    //Modify response
    HttpResponseMessageProperty rmp = new HttpResponseMessageProperty();

    if (error is SecurityException &&
      (error.Message == "Session expired" || error.Message == "Authentication ticket expired"))
    {
      rmp.StatusCode = HttpStatusCode.Unauthorized;
      rmp.StatusDescription = "Unauthorized";
    }
    else
    {
      // return custom error code, 400.
      rmp.StatusCode = HttpStatusCode.BadRequest;
      rmp.StatusDescription = "Bad request";
    }

    //Mark the jsonerror and json content
    rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
    rmp.Headers["jsonerror"] = "true";

    //Add to fault
    fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);

  } 
}

以及我为服务添加自定义错误处理程序的位置

public class JsonWebScriptServiceHostFactory : WebScriptServiceHostFactory
{
  private static readonly ILog log =
   LogManager.GetLogger(System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType);

  protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
  {
    log.IfDebug("JsonWebScriptServiceHostFactory: creating service host");
    ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);
    host.Description.Behaviors.Add(new JsonErrorHandler());
    return host;
  } 
}

和自定义错误

[DataContract(Namespace = "VSS.Nighthawk.Foreman", Name = "JsonError")]
public class JsonError
{
  [DataMember]
  public string Message { get; set; }

  [DataMember]
  public string Source { get; set; }

  [DataMember]
  public string Detail { get; set; }
}
4

1 回答 1

0

您使用的是什么绑定和编码器,您在它们上配置了哪些设置?另外,您插入了什么行为?如果您已经插入了 WebScriptEnablingBehavior(因为 WebScriptServiceHostFactory 会自动插入),那么您的问题可能是 WSEB 插入了它自己的错误处理程序,它会做很多与您尝试做的事情相同的事情。

我还要做的是使用 Reflector 并查看嵌入在 WebScriptEnablingBehavior 中的错误处理程序,看看你在做什么不同,以及你是否可以做任何你还没有做的事情。这是一个非常非常棘手和毛茸茸的领域,有许多微妙之处,所以你可能没有第一次得到正确的错误处理程序。

您可能还必须完全停止使用 WebScriptEnablingBehavior(如果您正在使用它)——所以请确保您没有使用它。您可能需要从头开始重新实现 WebScriptEnablingBehavior 而不是您自己的,并将其从头插入到您的服务主机工厂中,而不是仅插入 JSON 错误处理程序。

希望这可以帮助!

于 2012-04-26T18:49:13.430 回答