调试WCF和Web客户端通信

时间:2014-05-17 19:21:43

标签: .net wcf

我们可以调试WCF和Web客户端之间交换的请求数据和响应数据吗?如果可以,请告诉我如何。 我的实际要求是我希望能够操纵(应用正则表达式/删除空字符)WCF发送的响应。

请告知。

2 个答案:

答案 0 :(得分:1)

我为此目的使用IClientMessageInspector取得了巨大成功。它允许您在继续通过WCF客户端之前查看请求/回复并进行编辑。 MSDN documentation对如何使用它非常清楚,但这里是基本部分(在C#中):

1)实现IClientMessageInspector的类。您可以使用传递给您的replyrequest对象进行查看和编辑:

public class MyMessageInspector : IClientMessageInspector
{
    public void AfterReceiveReply(
        ref Message reply, 
        object correlationState)
    {
        Console.WriteLine(
        "Received the following reply: '{0}'", reply.ToString());
    }

    public object BeforeSendRequest(
        ref Message request, 
        IClientChannel channel)
    {
        Console.WriteLine(
        "Sending the following request: '{0}'", request.ToString());
        return null;
    }
}

2)实现IEndpointBehavior的类,您将MyMessageInspector添加到端点行为中:

public class MyBehavior : IEndpointBehavior
{
    public void AddBindingParameters(
        ServiceEndpoint endpoint,
        BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(
        ServiceEndpoint endpoint, 
        ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new MyMessageInspector());
    }

    public void ApplyDispatchBehavior(
        ServiceEndpoint endpoint, 
        EndpointDispatcher endpointDispatcher)
    {
    }

    public void Validate(
        ServiceEndpoint endpoint)
    {
    }
}

3)最后,像这样将MyBehavior添加到您的端点(假设您已经配置了客户端和配置文件):

client.Endpoint.Behaviors.Add(new MyBehavior());

这将捕获通过给定客户端端点的所有请求/回复。

答案 1 :(得分:0)

为了拦截并可能调整参数并返回WCF调用的对象,您可以使用IOperationsInvoker和IOperationBehavior的自定义实现。有关此示例以及WCF中的其他可扩展性可能性,请查看以下article

关于你的问题的另一个概念:标题和文字并不完全匹配。在标题中你编写了Debugging,而在文本中你提到了对返回对象的调整,这不仅仅是一个调试。如果您只想调试参数并返回对象,即查看它们,您可能会发现更适合打开WCF跟踪。

相关问题