[WCF programming] 6. Binding behavior, wcf binding

Source: Internet
Author: User

[WCF programming] 6. Binding behavior, wcf binding
I. Binding behavior Overview

To support other local features of the server, WCF defines the concept of behavior. Behavior is the local feature of the service and does not affect the communication mode of the service. The client does not know the server behavior, so the behavior does not appear in the metadata bound to and published by the Service. The difference between "Contract" and "Behavior" in WCF: A Contract involves bilateral descriptions (a Contract is a means for service providers to interact with service consumers ), the behavior is based on the description of a single side. The client behavior reflects how WCF calls services, while the server behavior reflects the request Distribution Method of WCF. Therefore, the service contract is published externally through metadata, while the WCF Service behavior is transparent to the client.

By applying behavior to different parts of the system, you can control activities such as session management, concurrency, Throttling, and transactions in WCF. Some of these activities can only be applied at a certain level, such as the service level, endpoint level, operation level, and contract level.

You can set the behavior in different ways for different levels. Most actions can be set through configuration or features in configuration. Although most actions can be set by configuring parameters, some actions must be set in the code.

Ii. Service Behavior

With the [ServiceBehavior] feature, you can apply rules and behaviors at the service level. During design, the following attributes can be used to control the concurrency, instantiation, throttling, transactions, sessions, and threads of behaviors:

  • AddressFilterMode: allows you to modify the message filter. The AddressFilterMode attribute has three values: Any (WCF disables the address-based message filtering mechanism, which allows the routing service To process the target address (WS-Addressing <To> header, applies to message routing) request messages that are inconsistent with the current endpoint) and Exact (a filter that indicates Exact matching of the address of the incoming message), Prefix (indicates the filter that executes the longest Prefix match for the address of the incoming message), the default value is Exact.
  • AutomaticSessionShutdown: the default value of AutomaticSessionShutdown is true. When the agent is disabled, the session is terminated. If it is set to false, the session continues until the service explicitly closes its sending channel, so that the session lifecycle can be controlled.
  • ConcurrencyMode: You can use this parameter to set whether the service runs in a single thread or multiple threads. The default value is Single. Setting it to Multiple means thread security must be implemented in the service.
  • IgnoreExtensionDataObject: this parameter is a Boolean value. The default value is false. Setting it to true means that the message does not contain any unknown serialized data.
  • IncludeExceptionDetailInFaults: to send unprocessed exceptions to the client as SOAP messages, set this message parameter to true. In the development environment, you need to set this parameter to true; in the production environment, you need to set it to false.
  • InstanceContextMode: This attribute can be used to set the life cycle of a service instance. Its value can be set to PerCall (new System. serviceModel. the InstanceContext object is created before each call and recycled after the call) and PerSession (creates a new System for each session. serviceModel. instanceContext object), Single (only one System. serviceModel. the InstanceContext object is used for all incoming calls and is not recycled after the call. If the service object does not exist, create one). The default value is PerSession. Detailed information about strength management will be discussed later.
  • MaxItemsInObjectGraph: This attribute is used to set the maximum number of items that can appear in the serialized and deserialized object graphs.
  • ReleaseServiceInstanceOnTransactionComplete: If this parameter is set to true, the service object is released after the active transaction ends.
  • TransactionAutoCompleteOnSessionClose: If you want to end the current active transaction when the session is normally closed by the client, set this parameter to true.
  • TransactionIsolationLevel: Specifies the isolation level of the current object when the transaction is active. Chaos (cannot overwrite the pending changes in a transaction with a higher isolation level) and ReadCommitted (variable data can be read during a transaction, but cannot be modified) readUncommitted (variable data can be read and modified during the transaction) and RepeatableRead (variable data can be read but cannot be modified during the transaction. New data can be added during the transaction), Serializable (variable data can be read during the transaction, but cannot be modified, or any new data can be added), and Snapshot (variable data can be read. Before the transaction modifies the data, it verifies whether the data has been changed by another transaction after it initially reads the data. If the data has been updated, an error is thrown. In this way, the transaction can obtain the previously committed data value), Unspecified (the isolation level is different from the specified isolation level, but this level cannot be determined. If this value is set, an exception is thrown ).
  • TransactionTimeout: sets the transaction timeout time. After this time is exceeded, the transaction is considered to have been aborted and the rollback process is activated.
  • UseSynchronizationContext: Specifies whether to use the current synchronization context to select the thread for execution.
  • ValidateMustUnderstand: This attribute is used to disable the validation of the SOAP header marked as MustUnderstand. The default value is true.
Iii. Operation Behavior

OperationBehavior can be used to control certain aspects of the service. Actions that can be controlled at the operation level include transaction behavior, visitor identity recognition behavior, and object collection behavior.

  • AutoDisposeParameters: This attribute allows an operation to automatically release input, output, and reference parameters. The default value is false.
  • Impersonation: Sometimes operations must be performed as visitors. To meet this requirement, you need to set this attribute to Required or Allowed.
  • ReleaseInstanceMode: This attribute allows you to overwrite the InstanceContextMode recycle value of the current service object. Possible values include None (reclaim Objects Based on InstanceContextMode values), BeforeCall (reclaim objects before the call operation), and AfterCall (reclaim objects after the operation is completed), BeforeAndAfterCall (reclaim objects before and after the call operation is completed ). The default value is None.
  • TransactionAutoComplete: when the transaction starts, if the current method does not produce an error, this attribute will mark the current transaction as ended; otherwise, the transaction will be abandoned. When this attribute is set to false, you must manually mark the transaction as ending or giving up.
  • TransactionScopeRequired: This attribute determines whether a transaction is requested by the current method.

OperationBehavior can be used to control parameters closely related to service operations. You only need to apply this feature to the operations to be managed, and then set the attribute parameters of the behavior according to the specific needs to get the desired behavior. The Code is as follows:

[OperationBehavior(AutoDisposeParameters=true,            Impersonation=ImpersonationOption.NotAllowed,            ReleaseInstanceMode=ReleaseInstanceMode.None,            TransactionAutoComplete=true,            TransactionScopeRequired=false)]public void SayOneWay(string str){    Console.WriteLine(str);}

In the above example, all the attributes of the OperationBehavior feature take the default value.

Iv. endpoints

Although the service behavior is only useful on the server, the endpoint behavior can be applied to both all services and clients. Setting appropriate behavior for the endpoint allows you to manage the parameters of the serializer used by the client certificate. WCF provides a set of predefined behaviors, each of which can implement the System. ServiceModel. Description. IEndpointBehavior interface:

  • AddBindingParameters: use this behavior to check the current service description and modify the binding parameters based on the requirements of the endpoint behavior. This method can be called only once for each endpoint.
  • ApplyDispatchBehavior: the most important method of the IEndpointBehavior interface. It can be used to apply the behavior logic of the endpoint to the server.
  • Validate: This method is used to check the service description. An exception is thrown when the service description cannot meet the endpoint behavior requirements.

You can set different on termination points through configuration files, programming, or combination of the two. Unlike service behavior, the endpoint behavior can be used either on the client or on the server. Some special implementations can only be applied to clients, such as ClientCredential.

You can use the configuration file to define and configure endpoints. For example, on the client, if you want to provide a certificate when calling the relevant endpoint, you can use ClientCredential behavior, as shown in the following code: client configuration file

<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <startup> <supportedRuntime version = "v4.0" sku = ". NETFramework, Version = v4.5 "/> </startup> <system. serviceModel> <bindings> <wsHttpBinding> <binding name = "WSHttpBinding_IHelloWorldService"/> </wsHttpBinding> </bindings> <client> <endpoint address = "http: // localhost: 8000/HelloWorldService "binding =" wsHttpBinding "bindingConfiguration =" WSHttpBinding_IHelloWorldService "contract =" IHelloWorldService "name =" WSHttpBinding_IHelloWorldService"BehaviorConfiguration = "carexternalendpointbehavior"><Identity> <userPrincipalName value = "\ 001"/> </identity> </endpoint> </client> <behaviors><EndpointBehaviors> <behavior name = "inherit"> <clientCredentials> <clientCertificate findValue = "CN = client_cert" storeLocation = "CurrentUser" storeName = "My" Principal = "principal"/> </clientCredentials> </behavior> </endpointBehaviors></Behaviors> </system. serviceModel> </configuration>

For more information about certificate security, see use X509 certificates in WCF. For more information about certificate security, see here.

V. Contractual Behaviors

By implementing the System. ServiceModel. Description. IContractBehavior interface, you can extend or modify all aspects of the contract. This method is suitable for the entire contract cycle. This interface has four methods, all of which can be used for contract modification. Contract behavior cannot be used in the configuration file. Therefore, contract behavior can only be modified in the code or through attributes. The four methods of the System. ServiceModel. Description. IContractBehavior interface are as follows:

  • AddBindingParameters: This method allows you to add custom parameters, which are often used to control the execution of behaviors. This method can be executed only once for each endpoint.
  • ApplyClientBehavior: You can use this method to apply the behavior logic on the client.
  • ApplyDispatchBehavior: You can use this method to apply the behavior logic on the service client.
  • Validate: used to verify the runtime context During behavior execution.

For IEndpointBehavior, IContractBehavior can be applied to both the client of the Contract interface and the server of the Contract interface. However, an IContractBehavior implementation cannot be modified through the configuration file at run time, but can only be added through attributes or programming methods at design time.

[DeliveryRequirements(QueuedDeliveryRequirements=QueuedDeliveryRequirementsMode.NotAllowed,RequireOrderedDelivery=true)]public class HelloWorldService : IHelloWorldService{      //}
In the preceding example, DeliveryRequirements indicates that the contract is not sent in sequence, but that the message is sent in order.
Reference books: WCF 4 Advanced Programming

Can a Chinese tank launch a laser-guided bomb?
Can I score a question?

If you have a reward of less than 10 for your questions, you will receive (10-reward points) points when dealing with expired questions.

Related Article

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.