IClientMessageInspector IDispatchMessageInspector
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ServiceModel; using System.ServiceModel.Dispatcher; using System.ServiceModel.Description; using System.ServiceModel.Channels; namespace MyLib { /// <summary> /// 消息拦截器 /// </summary> public class MyMessageInspector:IClientMessageInspector,IDispatchMessageInspector { void IClientMessageInspector.AfterReceiveReply(ref Message reply, object correlationState) { Console.WriteLine("客户端接收到的回复:\n{0}", reply.ToString()); } object IClientMessageInspector.BeforeSendRequest(ref Message request, IClientChannel channel) { Console.WriteLine("客户端发送请求前的SOAP消息:\n{0}", request.ToString()); return null; } object IDispatchMessageInspector.AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { Console.WriteLine("服务器端:接收到的请求:\n{0}", request.ToString()); return null; } void IDispatchMessageInspector.BeforeSendReply(ref Message reply, object correlationState) { Console.WriteLine("服务器即将作出以下回复:\n{0}", reply.ToString()); } } /// <summary> /// 插入到终结点的Behavior /// </summary> public class MyEndPointBehavior : IEndpointBehavior { public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { // 不需要 return; } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { // 植入“偷听器”客户端 clientRuntime.ClientMessageInspectors.Add(new MyMessageInspector()); } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { // 植入“偷听器” 服务器端 endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new MyMessageInspector()); } public void Validate(ServiceEndpoint endpoint) { // 不需要 return; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Description; namespace WCFServer { class Program { static void Main(string[] args) { // 服务器基址 Uri baseAddress = new Uri("http://localhost:1378/services"); // 声明服务器主机 using (ServiceHost host = new ServiceHost(typeof(MyService), baseAddress)) { // 添加绑定和终结点 WSHttpBinding binding = new WSHttpBinding(); host.AddServiceEndpoint(typeof(IService), binding, "/test"); // 添加服务描述 host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true }); // 把自定义的IEndPointBehavior插入到终结点中 foreach (var endpont in host.Description.Endpoints) { endpont.EndpointBehaviors.Add(new MyLib.MyEndPointBehavior()); } try { // 打开服务 host.Open(); Console.WriteLine("服务已启动。"); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); } } } [ServiceContract(Namespace = "MyNamespace")] public interface IService { [OperationContract] int AddInt(int a, int b); [OperationContract] Student GetStudent(); [OperationContract] CalResultResponse ComputingNumbers(CalcultRequest inMsg); } [ServiceBehavior(IncludeExceptionDetailInFaults = true)] public class MyService : IService { public int AddInt(int a, int b) { return a + b; } public Student GetStudent() { Student stu = new Student(); stu.StudentName = "小明"; stu.StudentAge = 22; return stu; } public CalResultResponse ComputingNumbers(CalcultRequest inMsg) { CalResultResponse rmsg = new CalResultResponse(); switch (inMsg.Operation) { case "加": rmsg.ComputedResult = inMsg.NumberA + inMsg.NumberB; break; case "减": rmsg.ComputedResult = inMsg.NumberA - inMsg.NumberB; break; case "乘": rmsg.ComputedResult = inMsg.NumberA * inMsg.NumberB; break; case "除": rmsg.ComputedResult = inMsg.NumberA / inMsg.NumberB; break; default: throw new ArgumentException("运算操作只允许加、减、乘、除。"); break; } return rmsg; } } [DataContract] public class Student { [DataMember] public string StudentName; [DataMember] public int StudentAge; } [MessageContract] public class CalcultRequest { [MessageHeader] public string Operation; [MessageBodyMember] public int NumberA; [MessageBodyMember] public int NumberB; } [MessageContract] public class CalResultResponse { [MessageBodyMember] public int ComputedResult; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WCFClient { class Program { static void Main(string[] args) { WS.ServiceClient client = new WS.ServiceClient(); // 记得在客户端也要插入IEndPointBehavior client.Endpoint.EndpointBehaviors.Add(new MyLib.MyEndPointBehavior()); try { // 1、调用带元数据参数和返回值的操作 Console.WriteLine("\n20和35相加的结果是:{0}", client.AddInt(20, 35)); // 2、调用带有数据协定的操作 WS.Student student = client.GetStudent(); Console.WriteLine("\n学生信息---------------------------"); Console.WriteLine("姓名:{0}\n年龄:{1}", student.StudentName, student.StudentAge); // 3、调用带消息协定的操作 Console.WriteLine("\n15乘以70的结果是:{0}", client.ComputingNumbers("乘", 15, 70)); } catch (Exception ex) { Console.WriteLine("异常:{0}", ex.Message); } client.Close(); Console.ReadKey(); } } }
/// <summary> /// 消息拦截器 /// </summary> public class MyMessageInspector:IClientMessageInspector,IDispatchMessageInspector { void IClientMessageInspector.AfterReceiveReply(ref Message reply, object correlationState) { //Console.WriteLine("客户端接收到的回复:\n{0}", reply.ToString()); return; } object IClientMessageInspector.BeforeSendRequest(ref Message request, IClientChannel channel) { //Console.WriteLine("客户端发送请求前的SOAP消息:\n{0}", request.ToString()); // 插入验证信息 MessageHeader hdUserName = MessageHeader.CreateHeader("u", "fuck", "admin"); MessageHeader hdPassWord = MessageHeader.CreateHeader("p", "fuck", "123"); request.Headers.Add(hdUserName); request.Headers.Add(hdPassWord); return null; } object IDispatchMessageInspector.AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { //Console.WriteLine("服务器端:接收到的请求:\n{0}", request.ToString()); // 栓查验证信息 string un = request.Headers.GetHeader<string>("u", "fuck"); string ps = request.Headers.GetHeader<string>("p", "fuck"); if (un == "admin" && ps == "abcd") { Console.WriteLine("用户名和密码正确。"); } else { throw new Exception("验证失败,滚吧!"); } return null; } void IDispatchMessageInspector.BeforeSendReply(ref Message reply, object correlationState) { //Console.WriteLine("服务器即将作出以下回复:\n{0}", reply.ToString()); return; } }