1

我在服务端做了一个自定义错误处理程序:

 public class GlobalErrorHandler : Attribute, IErrorHandler, IServiceBehavior
    {
        public void AddBindingParameters(
            ServiceDescription serviceDescription,
            ServiceHostBase serviceHostBase,
            Collection<ServiceEndpoint> endpoints,
            BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            IErrorHandler errorHandler = new GlobalErrorHandler();

            foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
            {
                ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;

                if (channelDispatcher != null)
                {
                    channelDispatcher.ErrorHandlers.Add(errorHandler);

                }
            }
        }

        public bool HandleError(Exception error)
        {
            Trace.TraceError(error.ToString());

            if (error is FaultException)
                return false; // Let WCF do normal processing
            else
                return true; // Fault message is already generated
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
        }

        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            if (error is FaultException)
            {
                // Let WCF do normal processing
            }
            else
            {
                // Generate fault message manually
                MessageFault messageFault = MessageFault.CreateFault(
                    new FaultCode("Sender"), new FaultReason(error.Message),
                    error, new NetDataContractSerializer());
                fault = Message.CreateMessage(version, messageFault, null);
            }
        }

    }

    public class ErrorHandlerElement : BehaviorExtensionElement
    {
        protected override object CreateBehavior()
        {
            return new GlobalErrorHandler();
        }

        public override Type BehaviorType
        {
            get { return typeof (GlobalErrorHandler); }
        }
    }

我在客户端定义了一个自定义消息检查器:

public class MessageInspector : IClientMessageInspector
    {
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            if (reply.IsFault)
            {
                //do some processing
            }
        }

        public object BeforeSendRequest(ref Message request, System.ServiceModel.IClientChannel channel)
        {
            return null;
        }
}

我有一个自定义行为,可以连接消息检查器:

public class NewtonsoftJsonBehavior : WebHttpBehavior
{
 public override void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime       clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(new MessageInspector());
        }
}

这种行为是通过工厂以编程方式应用的:

public class JsonWebServiceHostFactory : WebServiceHostFactory
    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            var host =  base.CreateServiceHost(serviceType, baseAddresses);
            //return host;
            //ServiceEndpoint ep = host.AddServiceEndpoint(serviceType, new WebHttpBinding(), "");
            //host.Description.Endpoints[0].Behaviors.Add(new WebHttpBehavior { HelpEnabled = true });     
            //return host;

            WebHttpBinding webBinding = new WebHttpBinding();

            host.AddServiceEndpoint(serviceType, webBinding, "").Behaviors.Add(new NewtonsoftJsonBehavior());
            return host;
        }
    }

但是,当我调试并在服务中生成错误异常时,会调用 globalerrorhandler,但调试器永远不会进入消息检查器。知道为什么吗?

4

2 回答 2

4

要在 WCF 服务端创建消息检查器,请使用实现IDispatchMessageInspector代替:IClientMessageInspector

一个例子:

服务:

EndpointAddress endpoint = new EndpointAddress("http://localhost:9001/Message");

WebServiceHost svcWebHost = new WebServiceHost(typeof(Service.Message), endpoint.Uri);

CustomServiceBehavior serviceBehavior = new CustomServiceBehavior();
svcWebHost.Description.Behaviors.Add(serviceBehavior);

Binding webHttpBinding = new WebHttpBinding();

ServiceEndpoint serviceEndpoint = svcWebHost.AddServiceEndpoint(typeof(Service.IMessage), webHttpBinding, endpoint.Uri);

ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
svcWebHost.Description.Behaviors.Add(smb);

ServiceDebugBehavior sdb = svcWebHost.Description.Behaviors.Find<ServiceDebugBehavior>();
sdb.IncludeExceptionDetailInFaults = true;

svcWebHost.Open();

服务合同

[ServiceContract]
public interface IMessage
{
    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    Model.TestResponse Test();
}

服务实施

public class Message : IMessage
{
    public Model.TestResponse Test()
    {
        return new Model.TestResponse() { success = true, message = "OK!" };
    }
}

CustomServiceBehavior 实现 IServiceBehavior:

public class CustomServiceBehavior : IServiceBehavior
{
    public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {

    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
    {
        CustomEndpointBehavior endpointBehavior = new CustomEndpointBehavior();
        foreach (var endpoint in serviceDescription.Endpoints)
            endpoint.EndpointBehaviors.Add(endpointBehavior);
    }

    public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
    {

    }
}

CustomEndpointBehavior 实现 IEndpointBehavior

public class CustomEndpointBehavior : IEndpointBehavior
{
    public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {

    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
    {

    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
    {
        var inspector = new CustomDispatchMessageInspector();
        endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
    }

    public void Validate(ServiceEndpoint endpoint)
    {

    }
}

CustomDispatchMessageInspector 实现 IDispatchMessageInspector

public class CustomDispatchMessageInspector : IDispatchMessageInspector
{
    public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
    {
        return null;
    }

    public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
        var httpResponse = ((HttpResponseMessageProperty)reply.Properties["httpResponse"]);
        httpResponse.Headers.Add("user-agent", "My Browser");
    }
}

此示例是一个 WCF 自托管,没有配置文件(在代码中配置 WCF 服务),它返回 Json 并在 HTTP 响应中发送自定义标头(用户代理:我的浏览器)。

要测试此代码:

  1. 创建 Windows 控制台应用程序
  2. 插入代码(一个类中的每个块)
  3. 运行应用程序
  4. 使用浏览器打开网址: http://localhost:9001/Message/Test
  5. 响应是一个 Json: {"message":"OK!","success":true}
  6. 您可以检查响应并查看自定义标头:“user-agent:My Browser”
于 2014-03-24T18:03:15.020 回答
0

您只需将消息检查器放在客户端使用ApplyClientBehavior. 服务端还有另一种方法:

public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
  if (endpointDispatcher != null)
  {
    endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new MessageInspector());
  }
}
于 2013-05-15T09:23:43.020 回答