AspNetCompatibilityRequirementsAttribute Classe

Definição

Aplicado a um serviço WCF (Windows Communication Foundation) para indicar se esse serviço pode ser executado no código de compatibilidade ASP.NET.Applied to a Windows Communication Foundation (WCF) service to indicate whether that service can be run in ASP.NET compatibility code.

public ref class AspNetCompatibilityRequirementsAttribute sealed : Attribute, System::ServiceModel::Description::IServiceBehavior
[System.AttributeUsage(System.AttributeTargets.Class)]
public sealed class AspNetCompatibilityRequirementsAttribute : Attribute, System.ServiceModel.Description.IServiceBehavior
[<System.AttributeUsage(System.AttributeTargets.Class)>]
type AspNetCompatibilityRequirementsAttribute = class
    inherit Attribute
    interface IServiceBehavior
Public NotInheritable Class AspNetCompatibilityRequirementsAttribute
Inherits Attribute
Implements IServiceBehavior
Herança
AspNetCompatibilityRequirementsAttribute
Atributos
Implementações

Exemplos

Os desenvolvedores de serviço podem garantir que seu serviço seja executado somente no modo de compatibilidade ASP.NET, definindo a RequirementsMode propriedade no AspNetCompatibilityRequirementsAttribute Required como mostrado no exemplo a seguirService developers can ensure that their service is only run in ASP.NET Compatibility Mode by setting the RequirementsMode property on the AspNetCompatibilityRequirementsAttribute to Required as shown in the following example

[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public interface ICalculatorSession
{
    [OperationContract]
    void Clear();
    [OperationContract]
    void AddTo(double n);
    [OperationContract]
    void SubtractFrom(double n);
    [OperationContract]
    void MultiplyBy(double n);
    [OperationContract]
    void DivideBy(double n);
    [OperationContract]
    double Equals();
}
<ServiceContract(Namespace:="http://Microsoft.ServiceModel.Samples")> _
Public Interface ICalculatorSession

    <OperationContract()> _
    Sub Clear()
    <OperationContract()> _
    Sub AddTo(ByVal n As Double)
    <OperationContract()> _
    Sub SubtractFrom(ByVal n As Double)
    <OperationContract()> _
    Sub MultiplyBy(ByVal n As Double)
    <OperationContract()> _
    Sub DivideBy(ByVal n As Double)
    <OperationContract()> _
    Function Equal() As Double
End Interface
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class CalculatorService : ICalculatorSession
{
    double result
    {   // Store result in AspNet session.
        get
        {
            if (HttpContext.Current.Session["Result"] != null)
                return (double)HttpContext.Current.Session["Result"];
            return 0.0D;
        }
        set
        {
            HttpContext.Current.Session["Result"] = value;
        }
    }

    public void Clear()
    {
    }

    public void AddTo(double n)
    {
        result += n;
    }

    public void SubtractFrom(double n)
    {
        result -= n;
    }

    public void MultiplyBy(double n)
    {
        result *= n;
    }

    public void DivideBy(double n)
    {
        result /= n;
    }

    public double Equals()
    {
        return result;
    }
}
    <AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Required)> _
    Public Class CalculatorService
        Implements ICalculatorSession

        Property Result() As Double
            ' Store result in AspNet Session.
            Get
                If (HttpContext.Current.Session("Result") Is Nothing) Then
                    Return 0D
                End If
                Return HttpContext.Current.Session("Result")
            End Get
            Set(ByVal value As Double)
                HttpContext.Current.Session("Result") = value
            End Set
        End Property

        Public Sub Clear() _
 Implements ICalculatorSession.Clear
            Result = 0D
        End Sub

        Public Sub AddTo(ByVal n As Double) _
Implements ICalculatorSession.AddTo
            Result += n
        End Sub

        Public Sub SubtractFrom(ByVal n As Double) _
Implements ICalculatorSession.SubtractFrom

            Result -= n
        End Sub

        Public Sub MultiplyBy(ByVal n As Double) _
Implements ICalculatorSession.MultiplyBy

            Result *= n
        End Sub

        Public Sub DivideBy(ByVal n As Double) _
Implements ICalculatorSession.DivideBy

            Result /= n
        End Sub

        Public Function Equal() As Double _
Implements ICalculatorSession.Equal

            Return Result
        End Function
    End Class

Comentários

Quando aplicado a uma classe de implementação de serviço, esse atributo indica se este serviço requer ou dá suporte ao modo de compatibilidade ASP.NET para ser habilitado para o AppDomain (domínio de aplicativo de hospedagem).When applied to a service implementation class, this attribute indicates whether this service requires or supports ASP.NET compatibility mode to be enabled for the hosting application domain (AppDomain).

Os AppDomains que hospedam serviços WCF podem ser executados em dois modos de hospedagem diferentes:AppDomains hosting WCF services can run in two different hosting modes:

  • Modo de transportes misto (padrão): nesse modo, os serviços WCF não participam do pipeline HTTP ASP.NET.Mixed Transports Mode (Default): In this mode, WCF services do not participate in the ASP.NET HTTP pipeline. Isso garante que um serviço WCF se comporta de forma consistente, independentemente do ambiente de hospedagem e do transporte.This guarantees that a WCF service behaves consistently, independent of hosting environment and transport.

  • Modo de compatibilidade de ASP.NET: nesse modo, os serviços WCF participam do pipeline HTTP ASP.NET de maneira semelhante aos serviços ASMX.ASP.NET Compatibility Mode: In this mode, WCF services participate in the ASP.NET HTTP pipeline in a manner similar to ASMX services. Os recursos de ASP.NET, como autorização de arquivo, UrlAuthorization e estado de sessão HTTP, são aplicáveis aos serviços WCF em execução neste modo.ASP.NET features such as File Authorization, UrlAuthorization, and HTTP Session State are applicable to WCF services running in this mode.

O modo de hospedagem é controlado pelo sinalizador de configuração de nível de aplicativo aspNetCompatibilityEnabled .The hosting mode is controlled by the application-level configuration flag aspNetCompatibilityEnabled.

<system.serviceModel>

<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

</system.serviceModel>

Esse sinalizador é false por padrão e, portanto, os serviços WCF são executados no modo de transportes mistos, a menos que você explicitamente opte pelo modo de compatibilidade ASP.net.This flag is false by default and thus WCF services run in the Mixed Transports Mode unless you explicitly opt into the ASP.NET compatibility mode.

Para obter mais informações sobre o modo de compatibilidade ASP.NET, consulte < ServiceHostingEnvironment > .For more information about ASP.NET compatibility mode, see <serviceHostingEnvironment>.

Use a RequirementsMode propriedade para fazer isso.Use the RequirementsMode property to do this. Em tempo de execução, os aplicativos podem detectar se o modo de compatibilidade ASP.NET está habilitado verificando o valor da propriedade estática AspNetCompatibilityEnabled .At runtime, applications can detect if ASP.NET compatibility mode is enabled by checking the value of the static property AspNetCompatibilityEnabled.

Construtores

AspNetCompatibilityRequirementsAttribute()

Inicializa uma nova instância da classe AspNetCompatibilityRequirementsAttribute.Initializes a new instance of the AspNetCompatibilityRequirementsAttribute class.

Propriedades

RequirementsMode

Obtém ou define o nível de compatibilidade de ASP.NET exigido pelo serviço.Gets or sets the level of ASP.NET compatibility required by the service.

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)

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)
IServiceBehavior.AddBindingParameters(ServiceDescription, ServiceHostBase, Collection<ServiceEndpoint>, BindingParameterCollection)

Adiciona dados personalizados que os elementos de associação podem acessar para dar suporte à implementação do contrato.Adds custom data that the binding elements can access to support the implementation of the contract.

IServiceBehavior.ApplyDispatchBehavior(ServiceDescription, ServiceHostBase)

Verifica se o tipo de hospedagem é consistente com os requisitos de compatibilidade do ASP.NET.Checks that the type of hosting is consistent with the ASP.NET compatibility requirements.

IServiceBehavior.Validate(ServiceDescription, ServiceHostBase)

Valida o comportamento do serviço.Validates the service behavior.

Aplica-se a