IPolicyImportExtension.ImportPolicy Método

Definição

Define um método que pode importar asserções de políticas personalizadas e adicionar elementos de ligação de implementação.

public:
 void ImportPolicy(System::ServiceModel::Description::MetadataImporter ^ importer, System::ServiceModel::Description::PolicyConversionContext ^ context);
public void ImportPolicy(System.ServiceModel.Description.MetadataImporter importer, System.ServiceModel.Description.PolicyConversionContext context);
abstract member ImportPolicy : System.ServiceModel.Description.MetadataImporter * System.ServiceModel.Description.PolicyConversionContext -> unit
Public Sub ImportPolicy (importer As MetadataImporter, context As PolicyConversionContext)

Parâmetros

importer
MetadataImporter

O MetadataImporter objeto em uso.

context
PolicyConversionContext

O PolicyConversionContext que contém tanto as asserções políticas que podem ser importadas como as coleções de elementos de ligação às quais elementos de ligação de implementação podem ser adicionados.

Exemplos

O seguinte exemplo de código mostra o uso do PolicyAssertionCollection.Remove método para localizar, devolver e remover a asserção num só passo.

  #region IPolicyImporter Members
  public const string name1 = "acme";
  public const string ns1 = "http://Microsoft/WCF/Documentation/CustomPolicyAssertions";

  /*
   * Importing policy assertions usually means modifying the bindingelement stack in some way
   * to support the policy assertion. The procedure is:
   * 1. Find the custom assertion to import.
   * 2. Insert a supporting custom bindingelement or modify the current binding element collection
   *     to support the assertion.
   * 3. Remove the assertion from the collection. Once the ImportPolicy method has returned,
   *     any remaining assertions for the binding cause the binding to fail import and not be
   *     constructed.
   */
  public void ImportPolicy(MetadataImporter importer, PolicyConversionContext context)
  {
    Console.WriteLine("The custom policy importer has been called.");
    // Locate the custom assertion and remove it.
    XmlElement customAssertion = context.GetBindingAssertions().Remove(name1, ns1);
    if (customAssertion != null)
    {
      Console.WriteLine(
        "Removed our custom assertion from the imported "
        + "assertions collection and inserting our custom binding element."
      );
      // Here we would add the binding modification that implemented the policy.
      // This sample does not do this.
      Console.ForegroundColor = ConsoleColor.Red;
      Console.WriteLine(customAssertion.NamespaceURI + " : " + customAssertion.Name);
      Console.WriteLine(customAssertion.OuterXml);
      Console.ForegroundColor = ConsoleColor.Gray;
    }
 }
#endregion
    #Region "IPolicyImporter Members"
    Public Const name1 As String = "acme"
    Public Const ns1 As String = "http://Microsoft/WCF/Documentation/CustomPolicyAssertions"

'    
'     * Importing policy assertions usually means modifying the bindingelement stack in some way
'     * to support the policy assertion. The procedure is:
'     * 1. Find the custom assertion to import.
'     * 2. Insert a supporting custom bindingelement or modify the current binding element collection
'     *     to support the assertion.
'     * 3. Remove the assertion from the collection. Once the ImportPolicy method has returned, 
'     *     any remaining assertions for the binding cause the binding to fail import and not be 
'     *     constructed.
'     
    Public Sub ImportPolicy(ByVal importer As MetadataImporter, ByVal context As PolicyConversionContext) Implements IPolicyImportExtension.ImportPolicy
      Console.WriteLine("The custom policy importer has been called.")
      ' Locate the custom assertion and remove it.
      Dim customAssertion As XmlElement = context.GetBindingAssertions().Remove(name1, ns1)
      If customAssertion IsNot Nothing Then
        Console.WriteLine("Removed our custom assertion from the imported " & "assertions collection and inserting our custom binding element.")
        ' Here we would add the binding modification that implemented the policy.
        ' This sample does not do this.
        Console.ForegroundColor = ConsoleColor.Red
        Console.WriteLine(customAssertion.NamespaceURI & " : " & customAssertion.Name)
        Console.WriteLine(customAssertion.OuterXml)
        Console.ForegroundColor = ConsoleColor.Gray
      End If
    End Sub
  #End Region

O exemplo de código seguinte mostra que o ficheiro de configuração da aplicação cliente carrega o importador de políticas personalizadas quando é System.ServiceModel.Description.MetadataResolver invocado.

<client>
    <endpoint 
      address="http://localhost:8080/StatefulService" 
      binding="wsHttpBinding"
      bindingConfiguration="CustomBinding_IStatefulService" 
      contract="IStatefulService"
      name="CustomBinding_IStatefulService" />
  <metadata>
    <policyImporters>
      <extension type="Microsoft.WCF.Documentation.CustomPolicyImporter, PolicyExtensions"/>
    </policyImporters>
  </metadata>
</client>

O exemplo de código seguinte mostra a utilização do MetadataResolver para descarregar e resolver metadados em objetos de descrição.

// Download all metadata.
ServiceEndpointCollection endpoints
  = MetadataResolver.Resolve(
    typeof(IStatefulService),
    new EndpointAddress("http://localhost:8080/StatefulService/mex")
  );
' Download all metadata. 
Dim endpoints As ServiceEndpointCollection = MetadataResolver.Resolve(GetType(IStatefulService), New EndpointAddress("http://localhost:8080/StatefulService/mex"))

Observações

Implementar o ImportPolicy método para obter declarações de apólice e realizar alguma modificação do contrato importado ou vinculativo para apoiar a afirmação. Normalmente, um importador de políticas responde à obtenção de uma asserção de política personalizada configurando ou inserindo um elemento de ligação na ligação que está a ser importada.

Windows Communication Foundation (WCF) passa dois objetos ao método ImportPolicy, um MetadataImporter e um PolicyConversionContext. Normalmente, o PolicyConversionContext objeto já contém as asserções de política para cada âmbito de ligação.

Uma IPolicyImportExtension implementação executa os seguintes passos:

  1. Localiza a asserção de política personalizada pela qual é responsável chamando os GetBindingAssertionsmétodos , GetMessageBindingAssertions, ou GetOperationBindingAssertions os métodos, dependendo do âmbito.

  2. Remove a afirmação da política da coleção de afirmações. O PolicyAssertionCollection.Remove método localiza, devolve e remove a afirmação num só passo.

  3. Modifica a pilha vinculativa ou o contrato adicionando um costume BindingElement obrigatório à BindingElements propriedade ou modificando a propriedade PolicyConversionContext.Contract .

O passo 2 é importante. Depois de todos os importadores de apólices terem sido chamados, a WCF verifica a existência de quaisquer afirmações de política que permaneçam. Se existir uma, a WCF assume que a importação da política não teve sucesso e não importa a ligação associada.

Aplica-se a