CallbackBehaviorAttribute Classe
Definição
Configura uma implementação de serviço de retorno de chamada em um aplicativo cliente.Configures a callback service implementation in a client application.
public ref class CallbackBehaviorAttribute sealed : Attribute, System::ServiceModel::Description::IEndpointBehavior
[System.AttributeUsage(System.AttributeTargets.Class)]
public sealed class CallbackBehaviorAttribute : Attribute, System.ServiceModel.Description.IEndpointBehavior
[<System.AttributeUsage(System.AttributeTargets.Class)>]
type CallbackBehaviorAttribute = class
inherit Attribute
interface IEndpointBehavior
Public NotInheritable Class CallbackBehaviorAttribute
Inherits Attribute
Implements IEndpointBehavior
- Herança
- Atributos
- Implementações
Exemplos
O exemplo de código a seguir mostra um CallbackBehaviorAttribute em um objeto de retorno de chamada que usa o SynchronizationContext objeto para determinar a qual thread realizar marshaling, a ValidateMustUnderstand propriedade para impor a validação de mensagem e a IncludeExceptionDetailInFaults propriedade para retornar exceções como FaultException objetos para o serviço para fins de depuração.The following code example shows a CallbackBehaviorAttribute on a callback object that uses the SynchronizationContext object to determine which thread to marshal to, the ValidateMustUnderstand property to enforce message validation, and the IncludeExceptionDetailInFaults property to return exceptions as FaultException objects to the service for debugging purposes.
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading;
namespace Microsoft.WCF.Documentation
{
[CallbackBehaviorAttribute(
IncludeExceptionDetailInFaults= true,
UseSynchronizationContext=true,
ValidateMustUnderstand=true
)]
public class Client : SampleDuplexHelloCallback
{
AutoResetEvent waitHandle;
public Client()
{
waitHandle = new AutoResetEvent(false);
}
public void Run()
{
// Picks up configuration from the configuration file.
SampleDuplexHelloClient wcfClient
= new SampleDuplexHelloClient(new InstanceContext(this), "WSDualHttpBinding_SampleDuplexHello");
try
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Enter a greeting to send and press ENTER: ");
Console.Write(">>> ");
Console.ForegroundColor = ConsoleColor.Green;
string greeting = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Called service with: \r\n\t" + greeting);
wcfClient.Hello(greeting);
Console.WriteLine("Execution passes service call and moves to the WaitHandle.");
this.waitHandle.WaitOne();
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Set was called.");
Console.Write("Press ");
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("ENTER");
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write(" to exit...");
Console.ReadLine();
}
catch (TimeoutException timeProblem)
{
Console.WriteLine("The service operation timed out. " + timeProblem.Message);
Console.ReadLine();
}
catch (CommunicationException commProblem)
{
Console.WriteLine("There was a communication problem. " + commProblem.Message);
Console.ReadLine();
}
}
public static void Main()
{
Client client = new Client();
client.Run();
}
public void Reply(string response)
{
Console.WriteLine("Received output.");
Console.WriteLine("\r\n\t" + response);
this.waitHandle.Set();
}
}
}
Imports System.ServiceModel
Imports System.ServiceModel.Channels
Imports System.Threading
Namespace Microsoft.WCF.Documentation
<CallbackBehaviorAttribute(IncludeExceptionDetailInFaults:= True, UseSynchronizationContext:=True, ValidateMustUnderstand:=True)> _
Public Class Client
Implements SampleDuplexHelloCallback
Private waitHandle As AutoResetEvent
Public Sub New()
waitHandle = New AutoResetEvent(False)
End Sub
Public Sub Run()
' Picks up configuration from the configuration file.
Dim wcfClient As New SampleDuplexHelloClient(New InstanceContext(Me), "WSDualHttpBinding_SampleDuplexHello")
Try
Console.ForegroundColor = ConsoleColor.White
Console.WriteLine("Enter a greeting to send and press ENTER: ")
Console.Write(">>> ")
Console.ForegroundColor = ConsoleColor.Green
Dim greeting As String = Console.ReadLine()
Console.ForegroundColor = ConsoleColor.White
Console.WriteLine("Called service with: " & Constants.vbCrLf & Constants.vbTab & greeting)
wcfClient.Hello(greeting)
Console.WriteLine("Execution passes service call and moves to the WaitHandle.")
Me.waitHandle.WaitOne()
Console.ForegroundColor = ConsoleColor.Blue
Console.WriteLine("Set was called.")
Console.Write("Press ")
Console.ForegroundColor = ConsoleColor.Red
Console.Write("ENTER")
Console.ForegroundColor = ConsoleColor.Blue
Console.Write(" to exit...")
Console.ReadLine()
Catch timeProblem As TimeoutException
Console.WriteLine("The service operation timed out. " & timeProblem.Message)
Console.ReadLine()
Catch commProblem As CommunicationException
Console.WriteLine("There was a communication problem. " & commProblem.Message)
Console.ReadLine()
End Try
End Sub
Public Shared Sub Main()
Dim client As New Client()
client.Run()
End Sub
Public Sub Reply(ByVal response As String) Implements SampleDuplexHelloCallback.Reply
Console.WriteLine("Received output.")
Console.WriteLine(Constants.vbCrLf & Constants.vbTab & response)
Me.waitHandle.Set()
End Sub
End Class
End Namespace
Comentários
Use o CallbackBehaviorAttribute atributo para configurar ou estender o comportamento de execução de uma implementação de contrato de retorno de chamada em um aplicativo cliente.Use the CallbackBehaviorAttribute attribute to configure or extend the execution behavior of a callback contract implementation in a client application. Esse atributo executa a mesma função para a classe de retorno de chamada como o ServiceBehaviorAttribute atributo com exceção de comportamento de instanciação e configurações de transação.This attribute performs the same function for the callback class as the ServiceBehaviorAttribute attribute with the exception of instancing behavior and transaction settings.
O CallbackBehaviorAttribute deve ser aplicado à classe que implementa o contrato de retorno de chamada.The CallbackBehaviorAttribute must be applied to the class that implements the callback contract. Se aplicado a uma implementação de contrato não duplex InvalidOperationException , uma exceção é lançada em tempo de execução.If applied to a non-duplex contract implementation an InvalidOperationException exception is thrown at runtime.
Observação
Você também pode usar o OperationBehaviorAttribute atributo para as implementações da operação de retorno de chamada.You can also use the OperationBehaviorAttribute attribute for the callback operation implementations. No entanto, se OperationBehaviorAttribute for usado em uma operação de retorno de chamada, a ReleaseInstanceMode Propriedade deverá ser None ou uma InvalidOperationException exceção será lançada em tempo de execução.However, if OperationBehaviorAttribute is used on a callback operation, the ReleaseInstanceMode property must be None or an InvalidOperationException exception is thrown at runtime.
As seguintes propriedades estão disponíveis:The following properties are available:
A AutomaticSessionShutdown Propriedade fecha automaticamente a sessão quando o canal é fechado e o retorno de chamada conclui o processamento de todas as mensagens restantes.The AutomaticSessionShutdown property automatically closes the session when the channel is closed and the callback has finished processing any remaining messages.
A ConcurrencyMode propriedade controla o modelo de Threading interno, habilitando o suporte para objetos de retorno de chamada reentrantes ou multithread.The ConcurrencyMode property controls the internal threading model, enabling support for reentrant or multithreaded callback objects.
A IgnoreExtensionDataObject propriedade permite que o tempo de execução ignore informações de serialização extras que não são necessárias para processar a mensagem.The IgnoreExtensionDataObject property enables the runtime to ignore extra serialization information that is not required to process the message.
A IncludeExceptionDetailInFaults propriedade especifica se as exceções não tratadas em um serviço são retornadas ao serviço como falhas de SOAP para fins de depuração.The IncludeExceptionDetailInFaults property specifies whether unhandled exceptions in a service are returned to the service as SOAP faults for debugging purposes.
Os MaxItemsInObjectGraph limites de propriedade no número de itens em um grafo de objeto que são serializados.The MaxItemsInObjectGraph property limits on the number of items in an object graph that are serialized.
A TransactionIsolationLevel propriedade especifica o nível de isolamento da transação ao qual o contrato dá suporte.The TransactionIsolationLevel property specifies the transaction isolation level that the contract supports.
A TransactionTimeout propriedade especifica o período de tempo no qual uma transação deve ser concluída ou anulada.The TransactionTimeout property specifies the time period within which a transaction must complete or it aborts.
A UseSynchronizationContext propriedade indica se as chamadas de método de entrada devem ser sincronizadas automaticamente usando o SynchronizationContext objeto atual.The UseSynchronizationContext property indicates whether to synchronize inbound method calls automatically using the current SynchronizationContext object.
A ValidateMustUnderstand propriedade informa ao sistema se ele deve confirmar se os cabeçalhos SOAP marcados como
MustUnderstandtêm, na verdade, foram compreendidos.The ValidateMustUnderstand property informs the system whether it should confirm that SOAP headers marked asMustUnderstandhave, in fact, been understood.
Construtores
| CallbackBehaviorAttribute() |
Inicializa uma nova instância da classe CallbackBehaviorAttribute.Initializes a new instance of the CallbackBehaviorAttribute class. |
Propriedades
| AutomaticSessionShutdown |
Especifica se uma sessão será fechada automaticamente quando um serviço fechar uma sessão duplex.Specifies whether to automatically close a session when a service closes a duplex session. |
| ConcurrencyMode |
Obtém ou define se um serviço dá suporte a um thread, vários threads ou chamadas reentrantes.Gets or sets whether a service supports one thread, multiple threads, or reentrant calls. |
| IgnoreExtensionDataObject |
Obtém ou define um valor que especifica se dados de serialização desconhecidos serão enviados na conexão.Gets or sets a value that specifies whether to send unknown serialization data onto the wire. |
| IncludeExceptionDetailInFaults |
Obtém ou define um valor que especifica que as exceções de execução gerais sem tratamento devem ser convertidas em um FaultException<TDetail> do tipo String e enviadas como uma mensagem de falha.Gets or sets a value that specifies that general unhandled execution exceptions are to be converted into a FaultException<TDetail> of type String and sent as a fault message. Defina-o como |
| MaxItemsInObjectGraph |
Obtém ou define o número máximo de itens permitidos em um objeto serializado.Gets or sets the maximum number of items allowed in a serialized object. |
| TransactionIsolationLevel |
Especifica o nível de isolamento da transação.Specifies the transaction isolation level. |
| TransactionTimeout |
Obtém ou define o período dentro do qual uma transação deve ser concluída.Gets or sets the period within which a transaction must complete. |
| TypeId |
Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.When implemented in a derived class, gets a unique identifier for this Attribute. (Herdado de Attribute) |
| UseSynchronizationContext |
Obtém ou define um valor que especifica se o contexto de sincronização atual deve ser usado para escolher o thread de execução.Gets or sets a value that specifies whether to use the current synchronization context to choose the thread of execution. |
| ValidateMustUnderstand |
Obtém ou define um valor que especifica se o sistema ou o aplicativo reforça o processamento de cabeçalho SOAP |
Métodos
| Equals(Object) |
Retorna um valor que indica se essa instância é igual a um objeto especificado.Returns a value that indicates whether this instance is equal to a specified object. (Herdado de Attribute) |
| GetHashCode() |
Retorna o código hash para a instância.Returns the hash code for this instance. (Herdado de Attribute) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| IsDefaultAttribute() |
Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Herdado de Attribute) |
| Match(Object) |
Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Herdado de Attribute) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
Implantações explícitas de interface
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.Maps a set of names to a corresponding set of dispatch identifiers. (Herdado de Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera as informações de tipo para um objeto, que pode ser usado para obter as informações de tipo para uma interface.Retrieves the type information for an object, which can be used to get the type information for an interface. (Herdado de Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1). (Herdado de Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fornece acesso a propriedades e métodos expostos por um objeto.Provides access to properties and methods exposed by an object. (Herdado de Attribute) |
| IEndpointBehavior.AddBindingParameters(ServiceEndpoint, BindingParameterCollection) |
Configura os elementos de associação para dar suporte ao comportamento de retorno de chamada.Configures the binding elements to support the callback behavior. |
| IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint, ClientRuntime) |
Configura o runtime do cliente para o suporte para o objeto de retorno de chamada.Configures the client runtime to support the callback object. |
| IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint, EndpointDispatcher) |
Implementação do método ApplyDispatchBehavior(ServiceEndpoint, EndpointDispatcher).Implementation of the ApplyDispatchBehavior(ServiceEndpoint, EndpointDispatcher) method. Esta implementação não tem nenhum efeito.This implementation has no effect. |
| IEndpointBehavior.Validate(ServiceEndpoint) |
Valida a descrição do ponto de extremidade antes de compilar o runtime.Validates the endpoint description prior to building the runtime. |