CustomBinding Classe
Definição
Define uma associação de uma lista de elementos de associação.Defines a binding from a list of binding elements.
public ref class CustomBinding : System::ServiceModel::Channels::Binding
public class CustomBinding : System.ServiceModel.Channels.Binding
[System.Windows.Markup.ContentProperty("Elements")]
public class CustomBinding : System.ServiceModel.Channels.Binding
type CustomBinding = class
inherit Binding
[<System.Windows.Markup.ContentProperty("Elements")>]
type CustomBinding = class
inherit Binding
Public Class CustomBinding
Inherits Binding
- Herança
- Atributos
Exemplos
O exemplo a seguir mostra como criar um CustomBinding objeto usando um ReliableSessionBindingElement e um HttpTransportBindingElementThe following example shows how to create a CustomBinding object using a ReliableSessionBindingElement and an HttpTransportBindingElement
Uri baseAddress = new Uri("http://localhost:8000/servicemodelsamples/service");
// Create a ServiceHost for the CalculatorService type and provide the base address.
using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress))
{
// Create a custom binding that contains two binding elements.
ReliableSessionBindingElement reliableSession = new ReliableSessionBindingElement();
reliableSession.Ordered = true;
HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();
httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
CustomBinding binding = new CustomBinding(reliableSession, httpTransport);
// Add an endpoint using that binding.
serviceHost.AddServiceEndpoint(typeof(ICalculator), binding, "");
// Add a MEX endpoint.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.HttpGetUrl = new Uri("http://localhost:8001/servicemodelsamples");
serviceHost.Description.Behaviors.Add(smb);
// Open the ServiceHostBase to create listeners and start listening for messages.
serviceHost.Open();
// The service can now be accessed.
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
serviceHost.Close();
}
Dim baseAddress As New Uri("http://localhost:8000/servicemodelsamples/service")
' Create a ServiceHost for the CalculatorService type and provide the base address.
Using serviceHost As New ServiceHost(GetType(CalculatorService), baseAddress)
' Create a custom binding that contains two binding elements.
Dim reliableSession As New ReliableSessionBindingElement()
reliableSession.Ordered = True
Dim httpTransport As New HttpTransportBindingElement()
httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous
httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard
Dim binding As New CustomBinding(reliableSession, httpTransport)
' Add an endpoint using that binding.
serviceHost.AddServiceEndpoint(GetType(ICalculator), binding, "")
' Add a MEX endpoint.
Dim smb As New ServiceMetadataBehavior()
smb.HttpGetEnabled = True
smb.HttpGetUrl = New Uri("http://localhost:8001/servicemodelsamples")
serviceHost.Description.Behaviors.Add(smb)
' Open the ServiceHostBase to create listeners and start listening for messages.
serviceHost.Open()
' The service can now be accessed.
Console.WriteLine("The service is ready.")
Console.WriteLine("Press <ENTER> to terminate service.")
Console.WriteLine()
Console.ReadLine()
' Close the ServiceHostBase to shutdown the service.
serviceHost.Close()
End Using
Comentários
Use uma associação personalizada quando uma das associações fornecidas pelo sistema não atender aos requisitos do seu serviço.Use a custom binding when one of the system-provided bindings does not meet the requirements of your service. Uma associação personalizada poderia ser usada, por exemplo, para habilitar o uso de um novo transporte ou um novo codificador em um ponto de extremidade de serviço.A custom binding could be used, for example, to enable the use of a new transport or a new encoder at a service endpoint.
Uma associação personalizada é construída usando uma das CustomBinding coleções de elementos de associação que são "empilhadas" em uma ordem específica:A custom binding is constructed using one of the CustomBinding from a collection of binding elements that are "stacked" in a specific order:
Na parte superior, há um opcional TransactionFlowBindingElement que permite transações de fluxo.At the top is an optional TransactionFlowBindingElement that allows flowing transactions.
Em seguida, é um opcional ReliableSessionBindingElement que fornece um mecanismo de sessão e ordenação, conforme definido na especificação de WS-ReliableMessaging.Next is an optional ReliableSessionBindingElement that provides a session and ordering mechanism as defined in the WS-ReliableMessaging specification. Essa noção de uma sessão pode cruzar os intermediários de transporte e SOAP.This notion of a session can cross SOAP and transport intermediaries.
A seguir está um elemento de associação de segurança opcional que fornece recursos de segurança como autorização, autenticação, proteção e confidencialidade.Next is an optional security binding element that provides security features like authorization, authentication, protection, and confidentiality. Os seguintes elementos de associação de segurança são fornecidos pelo Windows Communication Foundation (WCF):The following security binding elements are provided by Windows Communication Foundation (WCF):
Em seguida, estão os padrões de mensagem opcionais especificados por elementos de associação:Next are the optional message-patterns specified by binding elements:
Em seguida, estão os elementos de associação de atualizações/auxiliares de transporte opcionais:Next are the optional transport upgrades/helpers binding elements:
A seguir está um elemento de associação de codificação de mensagem necessário.Next is a required message encoding binding element. Você pode usar seu próprio transporte ou usar uma das seguintes associações de codificação de mensagem:You can use your own transport or use one of the following message encoding bindings:
Na parte inferior, há um elemento Transport necessário.At the bottom is a required transport element. Você pode usar seu próprio transporte ou usar um dos elementos de associação de transporte fornecidos pelo Windows Communication Foundation (WCF):You can use your own transport or use one of transport binding elements provided by Windows Communication Foundation (WCF):
A tabela a seguir resume as opções para cada camada.The following table summarizes the options for each layer.
| CamadaLayer | OpçõesOptions | ObrigatórioRequired |
|---|---|---|
| Fluxo de transaçõesTransaction Flow | TransactionFlowBindingElement | NãoNo |
| ConfiabilidadeReliability | ReliableSessionBindingElement | NãoNo |
| SegurançaSecurity | Simétrico, assimétrico Transport-LevelSymmetric, Asymmetric, Transport-Level | NãoNo |
| Alteração de formaShape Change | CompositeDuplexBindingElement | NãoNo |
| Atualizações de transporteTransport Upgrades | Fluxo SSL, fluxo do Windows, resolvedor de paresSSL stream, Windows stream, Peer Resolver | NãoNo |
| CodificaçãoEncoding | Texto, binário, MTOM, personalizadoText, Binary, MTOM, Custom | YesYes |
| TransportTransport | TCP, pipes nomeados, HTTP, HTTPS, tipos de MSMQ, personalizadoTCP, Named Pipes, HTTP, HTTPS, flavors of MSMQ, Custom | YesYes |
Além disso, você pode definir seus próprios elementos de ligação e inseri-los entre as camadas definidas anteriormente.In addition, you can define your own binding elements and insert them between any of the preceding defined layers.
Para obter uma discussão sobre como usar uma associação personalizada para modificar uma associação fornecida pelo sistema, consulte como: personalizar uma associação de System-Provided.For a discussion on how to use a custom binding to modify a system-provided binding, see How to: Customize a System-Provided Binding.
Observação
Ao chamar um serviço WCF criado com o .NET Framework 4,0 ou posterior de um aplicativo cliente WCF criado com .NET Framework 3,5 ou anterior, o arquivo de configuração gerado pelo svcutil.exe ou a adição de uma referência de serviço do Visual Studio conterá o atributo de validade na configuração de associação.When calling a WCF service built with .NET Framework 4.0 or later from a WCF client application built with .NET Framework 3.5 or earlier, the configuration file generated by svcutil.exe or adding a service reference from Visual Studio will contain the validity attribute in the binding configuration. Este atributo não é reconhecido pelo tempo de execução .NET Framework 3,5 e o aplicativo gerará um ConfigurationErrorsException com a mensagem "validade do atributo não reconhecido".This attribute is not recognized by the .NET Framework 3.5 runtime and the application will thrown an ConfigurationErrorsException with the message "Unrecognized attribute validity". Para solucionar esse problema, remova o atributo de validade da configuração de associação.To workaround this problem, remove the validity attribute from the binding configuration.
Construtores
| CustomBinding() |
Inicializa uma nova instância da classe CustomBinding.Initializes a new instance of the CustomBinding class. |
| CustomBinding(Binding) |
Inicializa uma nova instância da classe CustomBinding dos valores de uma associação especificada.Initializes a new instance of the CustomBinding class from the values of a specified binding. |
| CustomBinding(BindingElement[]) |
Inicializa a nova instância da classe CustomBinding de uma matriz de elementos de associação.Initializes a new instance of the CustomBinding class from an array of binding elements. |
| CustomBinding(IEnumerable<BindingElement>) |
Inicializa uma nova instância da classe CustomBinding com os elementos de associação de uma pilha de canais completa.Initializes a new instance of the CustomBinding class with the binding elements from a complete channel stack. |
| CustomBinding(String) |
Inicializa uma nova instância da classe CustomBinding.Initializes a new instance of the CustomBinding class. |
| CustomBinding(String, String, BindingElement[]) |
Inicializa uma nova instância da classe CustomBinding de uma matriz de elementos de associação com um nome e namespace especificados.Initializes a new instance of the CustomBinding class from an array of binding elements with a specified name and namespace. |
Propriedades
| CloseTimeout |
Obtém ou define o intervalo concedido para que uma conexão seja fechada antes que o transporte gere uma exceção.Gets or sets the interval of time provided for a connection to close before the transport raises an exception. (Herdado de Binding) |
| Elements |
Obtém os elementos de associação da associação personalizada.Gets the binding elements from the custom binding. |
| MessageVersion |
Obtém a versão de mensagem usada por clientes e serviços configurados com a associação.Gets the message version used by clients and services configured with the binding. (Herdado de Binding) |
| Name |
Obtém ou define o nome da associação.Gets or sets the name of the binding. (Herdado de Binding) |
| Namespace |
Obtém ou define o namespace de XML da associação.Gets or sets the XML namespace of the binding. (Herdado de Binding) |
| OpenTimeout |
Obtém ou define o intervalo concedido para que uma conexão seja aberta antes que o transporte gere uma exceção.Gets or sets the interval of time provided for a connection to open before the transport raises an exception. (Herdado de Binding) |
| ReceiveTimeout |
Obtém ou define o intervalo de tempo que uma conexão pode permanecer inativa, durante o qual nenhuma mensagem de aplicativo é recebida, antes de seu descarte.Gets or sets the interval of time that a connection can remain inactive, during which no application messages are received, before it is dropped. (Herdado de Binding) |
| Scheme |
Obtém o esquema de URI para transporte usado pela associação personalizada.Gets the URI scheme for transport used by the custom binding. |
| SendTimeout |
Obtém ou define o intervalo concedido para uma operação ser concluída antes de o transporte gerar uma exceção.Gets or sets the interval of time provided for a write operation to complete before the transport raises an exception. (Herdado de Binding) |
Métodos
| BuildChannelFactory<TChannel>(BindingParameterCollection) |
Cria a pilha de fábricas de canais no cliente que cria um tipo de canal especificado e que satisfaz os recursos especificados por uma coleção de parâmetros de associação.Builds the channel factory stack on the client that creates a specified type of channel and that satisfies the features specified by a collection of binding parameters. (Herdado de Binding) |
| BuildChannelFactory<TChannel>(Object[]) |
Cria a pilha de fábricas de canais no cliente que cria um tipo de canal especificado e que satisfaz os recursos especificados por uma matriz de objetos.Builds the channel factory stack on the client that creates a specified type of channel and that satisfies the features specified by an object array. (Herdado de Binding) |
| BuildChannelListener<TChannel>(BindingParameterCollection) |
Cria o ouvinte de canais no serviço que aceita um tipo de canal especificado e que satisfaz os recursos especificados por uma coleção de parâmetros de associação.Builds the channel listener on the service that accepts a specified type of channel and that satisfies the features specified by a collection of binding parameters. (Herdado de Binding) |
| BuildChannelListener<TChannel>(Object[]) |
Cria o ouvinte de canais no serviço que aceita um tipo de canal especificado e que satisfaz os recursos especificados.Builds the channel listener on the service that accepts a specified type of channel and that satisfies the features specified. (Herdado de Binding) |
| BuildChannelListener<TChannel>(Uri, BindingParameterCollection) |
Cria o ouvinte de canais no serviço que aceita um tipo de canal especificado e que satisfaz os recursos especificados.Builds the channel listener on the service that accepts a specified type of channel and that satisfies the features specified. (Herdado de Binding) |
| BuildChannelListener<TChannel>(Uri, Object[]) |
Cria o ouvinte de canais no serviço que aceita um tipo de canal especificado e que satisfaz os recursos especificados.Builds the channel listener on the service that accepts a specified type of channel and that satisfies the features specified. (Herdado de Binding) |
| BuildChannelListener<TChannel>(Uri, String, BindingParameterCollection) |
Cria o ouvinte de canais no serviço que aceita um tipo de canal especificado e que satisfaz os recursos especificados.Builds the channel listener on the service that accepts a specified type of channel and that satisfies the features specified. (Herdado de Binding) |
| BuildChannelListener<TChannel>(Uri, String, ListenUriMode, BindingParameterCollection) |
Cria o ouvinte de canais no serviço que aceita um tipo de canal especificado e que satisfaz os recursos especificados.Builds the channel listener on the service that accepts a specified type of channel and that satisfies the features specified. (Herdado de Binding) |
| BuildChannelListener<TChannel>(Uri, String, ListenUriMode, Object[]) |
Cria o ouvinte de canais no serviço que aceita um tipo de canal especificado e que satisfaz os recursos especificados.Builds the channel listener on the service that accepts a specified type of channel and that satisfies the features specified. (Herdado de Binding) |
| BuildChannelListener<TChannel>(Uri, String, Object[]) |
Cria o ouvinte de canais no serviço que aceita um tipo de canal especificado e que satisfaz os recursos especificados.Builds the channel listener on the service that accepts a specified type of channel and that satisfies the features specified. (Herdado de Binding) |
| CanBuildChannelFactory<TChannel>(BindingParameterCollection) |
Retorna um valor que indica se a associação atual pode criar uma pilha de fábricas de canais no cliente que satisfaz a coleção de parâmetros de associação especificados.Returns a value that indicates whether the current binding can build a channel factory stack on the client that satisfies the collection of binding parameters specified. (Herdado de Binding) |
| CanBuildChannelFactory<TChannel>(Object[]) |
Retorna um valor que indica se a associação atual pode criar uma pilha de fábricas de canais no cliente que satisfaz os requisitos especificados por uma matriz de objetos.Returns a value that indicates whether the current binding can build a channel factory stack on the client that satisfies the requirements specified by an object array. (Herdado de Binding) |
| CanBuildChannelListener<TChannel>(BindingParameterCollection) |
Retorna um valor que indica se a associação atual pode criar uma pilha de ouvintes de canais no serviço que satisfaça a coleção de parâmetros de associação especificados.Returns a value that indicates whether the current binding can build a channel listener stack on the service that satisfies the collection of binding parameters specified. (Herdado de Binding) |
| CanBuildChannelListener<TChannel>(Object[]) |
Retorna um valor que indica se a associação atual pode criar uma pilha de ouvintes de canais no serviço que satisfaça os critérios especificados em uma matriz de objetos.Returns a value that indicates whether the current binding can build a channel listener stack on the service that satisfies the criteria specified in an array of objects. (Herdado de Binding) |
| CreateBindingElements() |
Retorna uma coleção genérica de elementos de associação da associação personalizada.Returns a generic collection of the binding elements from the custom binding. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetProperty<T>(BindingParameterCollection) |
Retorna um objeto tipado solicitado, se presente, da camada apropriada na pilha de associação.Returns a typed object requested, if present, from the appropriate layer in the binding stack. (Herdado de Binding) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| ShouldSerializeName() |
Retorna se o nome da associação deve ser serializado.Returns whether the name of the binding should be serialized. (Herdado de Binding) |
| ShouldSerializeNamespace() |
Retorna se o namespace da associação deve ser serializado.Returns whether the namespace of the binding should be serialized. (Herdado de Binding) |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |