15 days proficient in WCF-9th day advanced gameplay-custom Behavior, wcfbehavior

Source: Internet
Author: User

15 days proficient in WCF-9th day advanced gameplay-custom Behavior, wcfbehavior

 

Finally I have watched the second phase of love guard, too sour, recommended link: http://www.iqiyi.com/a_19rrgublqh.html? Vfm = 2008_aldbd,

Let's look at this interesting Behavior.

 

I. Behavior: It's amazing.

In the previous article, I also clearly explained the entire wcf communication stream, and the Behavior can be inserted anywhere in the wcf communication stream, which is very cool and well utilized, let you go to heaven, do not use

Okay, let you go to hell... Next let's take a look at what behavior can be injected ??? First draw a diagram:

The figure above is probably the communication diagram of wcf. All the blue fonts are Behavior injection points. Both the Client and Service can be injected, it can also be divided into "Operation Level" and

"Endpoint level". Let's take a brief look at it.

 

2. endpoint level Behavior

You can also see that the message checker is placed at the Channel level, that is, it can monitor the inbound requests of the Client and Server, that is, all requests must be forwarded through it. If

In this case, can I freely modify, change, intercept inbound and outbound requests on this injection point, and use this feature to do a lot of things, for example, logging, recording statistics, etc.

Let's see how to use this ??? You only need to extends IEndpointBehavior and IDispatchMessageInspector, and then add EndpointBehaviors...

1. IDispatchMessageInspector

 1     public class MyDispatchMessageInspector : IDispatchMessageInspector 2     { 3         public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) 4         { 5             Console.WriteLine(request.ToString()); 6             return request; 7         } 8  9         public void BeforeSendReply(ref Message reply, object correlationState)10         {11             Console.WriteLine(reply.ToString());12         }13     }

2. IEndpointBehavior

 1     public class MyEndpointBehavior : IEndpointBehavior 2     { 3         public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) 4         { 5         } 6  7         public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime) 8         { 9         }10 11         public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)12         {13             endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new MyDispatchMessageInspector());14         }15 16         public void Validate(ServiceEndpoint endpoint)17         {18         }19     }

3. Add MyEndpointBehavior to the Host.

1 static void Main (string [] args) 2 {3 ServiceHost host = new ServiceHost (typeof (HomeService), new Uri ("http: // 127.0.0.1: 1920 ")); 4 5 host. addServiceEndpoint (typeof (IHomeService), new BasicHttpBinding (), "HomeServie"); 6 7 host. description. behaviors. add (new ServiceMetadataBehavior () {HttpGetEnabled = true}); 8 9 host. addServiceEndpoint (typeof (IMetadataExchange), MetadataExchangeBindings. createMe XHttpBinding (), "mex"); 10 11 host. description. endpoints [0]. endpointBehaviors. add (new MyEndpointBehavior (); 12 13 host. open (); 14 15 Console. writeLine ("service enabled !!! "); 16 17 Console. Read (); 18}

4. Finally, let's take a look at the service method.

1 public class HomeService: IHomeService2 {3 public string Update (string message) 4 {5 Console. writeLine ("my actions method:" + message); 6 7 return "my reply !!! "; 8} 9}

 

Let's take a look at the effect... In, you should see it. In my Action, there is a line of "inbound message" and "outbound message" before and after the method, isn't it great ???

 

3. Operation Level Behavior

From the summary at the beginning of the article, you should see that there are many Operation-level Behavior, including "IOperationInvoker" and "IParameterInspector",

"IDispatchMessageFormatter" and so on... Why do we need to wait for this term? It is very simple. In fact, there are still many built-in systems. Since it is Operation, it is necessary.

But it is for methods. Do you still remember how OperationContract is applied to methods ??? It's a feature, right?, in the same way, OperationBehavior is the same. How can this problem be solved ??

It is also very simple, just inherit Several Interfaces...

<1> IParameterInspector

In fact, there is nothing to say. Since it belongs to the Behavior under Operation, it is injected through features, and this IParameterInspector can achieve Model verification similar to Mvc. below

I will make a simple verification of the length of the Action parameter (the length cannot exceed 8 characters ).

1. IParameterInspector

1 public class MyIParameterInspector: IParameterInspector 2 {3 public int MaxLength {get; set;} 4 5 public MyIParameterInspector (int MaxLength) 6 {7 this. maxLength = MaxLength; 8} 9 10 /// <summary> 11 // outbound operation 12 /// </summary> 13 /// <param name = "operationName"> </ param> 14 /// <param name = "outputs"> </param> 15 /// <param name = "returnValue"> </param> 16 /// <param name = "correlationState"> </param> 17 public void AfterCall (string operationName, object [] outputs, object returnValue, object correlationState) 18 {19 20} 21 22 /// <summary> 23 // The inbound parameter 24 /// </summary> 25 /// <param name = "operationName"> </param> 26 // <param name = "inputs"> </param> 27 // <returns> </returns> 28 public object BeforeCall (string operationName, object [] inputs) 29 {30 foreach (var item in inputs) 31 {32 if (Convert. toString (item ). length> MaxLength) 33 {34 throw new Exception ("ticket, Length cannot exceed" + MaxLength + "Length"); 35} 36} 37 38 return null; 39} 40}

2. IOperationBehavior

 1 public class MyOperationBehavior : Attribute, IOperationBehavior 2     { 3         public int MaxLength { get; set; } 4  5         public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) 6         { 7  8         } 9 10         public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)11         {12 13         }14 15         public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)16         {17             dispatchOperation.ParameterInspectors.Add(new MyIParameterInspector(MaxLength));18         }19 20         public void Validate(OperationDescription operationDescription)21         {22 23         }24     }

3. Add the Attribute MyOperationBehavior to the Action.

1 public class HomeService: IHomeService 2 {3 [MyOperationBehavior (MaxLength = 5)] 4 public string Update (string message) 5 {6 Console. writeLine ("my actions method:" + message); 7 8 return "my reply !!! "; 9} 10}

4. Then I intentionally enter a character greater than 5 on the client to see how it works ???

1 public class Program1 2 {3 static void Main (string [] args) 4 {5 HomeServiceClient client = new HomeServiceClient (); 6 7 client. update ("I intentionally entered many characters, haha ..... "); 8 9 Console. Read (); 10} 11}

5. Finally, we can see that the final inbound message will throw an exception...

 

 

<2> how to play MessageFormatter and IOperationInvoker

The remaining two methods are similar. You only need to extends and add them to OperationBehavior. With the above idea, I think the following is not a problem to use...

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.