我们在第一个自定义behavior的示例中,在Service端定义了一个behavior,这是一个ParameterInspector。代码下载:WCFBehaviorSolution1.zip


我们也可以在Client定义一个ParameterInspector。这与Service是否自定义了behavior无关。所以,我们可以基于WCFBehaviorSolution0.zip​,也可以基于WCFBehaviorSolution1.zip。

这里,让我们基于WCFBehaviorSolution0.zip这个最简单的例子。


(一)创建类库CustomClientBehaviors,并建立MyParameterInspector 类,这个behavior是让输入参数自减1:

public class MyParameterInspector : IOperationBehavior, IParameterInspector
{
#region IOperationBehavior Members

public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{

}

public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{
clientOperation.ParameterInspectors.Add(this);
}

public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{

}

public void Validate(OperationDescription operationDescription)
{

}

#endregion

#region IParameterInspector Members

public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
{
Console.WriteLine("after the call.");
}

public object BeforeCall(string operationName, object[] inputs)
{
Console.WriteLine("before the call.");
inputs[0] = "BaoBao";
return null;
}

#endregion
}


(二)在项目ClientConsoleApplication中添加对类库CustomClientBehaviors的引用。然后打开ServiceReference1,找到Reference.cs:


 
修改其中带有一个参数的构造函数,我们把MyParameterInspector这个自定义行为添加到GetData方法(也就是Operations[0])上:
public Service1Client(string endpointConfigurationName) :
base(endpointConfigurationName)
{
base.Endpoint.Contract.Operations[0].Behaviors.Add(new MyParameterInspector());
}



(三)在Client端,也就是项目ClientConsoleApplication中,调用Service1Client带有参数的构造函数:

static void Main(string[] args)
{
ServiceReference1.Service1Client client = new ClientConsoleApplication.ServiceReference1.Service1Client("WSHttpBinding_IService1");

string price = client.GetData(1982);

Console.WriteLine(price);

Console.ReadKey(true);
}



注意这个参数,它是终结点的Name,我们查找app.config:

<endpoint address="​​http://localhost:8731/Design_Time_Addresses/WcfServiceLibrary1/Service1/"​​​

    binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"

    contract="ServiceReference1.IService1" name="WSHttpBinding_IService1">

发现这个值是WSHttpBinding_IService1,对,就把这个值作为上述构造函数的参数值。


运行这个程序,效果如下所示,我们在Client输入了参数1982,在传给Service之前就减少了1,变成了1981:


最终的代码示例下载:WCFBehaviorSolution2.zip