Поделиться через


IPolicyImportExtension Интерфейс

Определение

Определяет метод для объектов, импортируемых утверждения пользовательской политики о привязках.

public interface class IPolicyImportExtension
public interface IPolicyImportExtension
type IPolicyImportExtension = interface
Public Interface IPolicyImportExtension
Производный

Примеры

В следующем примере кода показано использование PolicyAssertionCollection.Remove метода для поиска, возврата и удаления утверждения на одном шаге.

  #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

В следующем примере кода показан файл конфигурации клиентского приложения для загрузки пользовательского импорта политик при System.ServiceModel.Description.MetadataResolver вызове.

<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>

В следующем примере кода показано использование метаданных MetadataResolver для скачивания и разрешения метаданных в объекты описания.

// 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"))

Комментарии

IPolicyImportExtension Реализуйте интерфейс для поиска сведений WSDL, предоставляемых определенной конечной точкой для утверждений пользовательской политики о возможностях или требованиях к конечной точке. Как правило, импорт политики выполняет поиск определенного утверждения и либо вставляет элемент привязки, настраивает элемент привязки, либо изменяет контракт для поддержки требований утверждения.

В отличие от своего аналога, IPolicyExportExtensionIPolicyImportExtension не требует реализации BindingElement объектом. Его можно загрузить с помощью раздела конфигурации клиента, показанного в разделе Examples или программным способом, добавив его в System.ServiceModel.Description.WsdlImporter конструктор.

Windows Communication Foundation (WCF) передает два объекта методу ImportPolicy , a MetadataImporter и a PolicyConversionContext. Обычно PolicyConversionContext объект уже содержит утверждения политики для каждой области привязки.

Реализация IPolicyImportExtension выполняет следующие действия.

  1. Находит утверждение настраиваемой политики, для которого она отвечает, вызывая GetBindingAssertionsGetMessageBindingAssertionsметоды или GetOperationBindingAssertions методы в зависимости от области.

  2. Удаляет утверждение политики из коллекции утверждений. Метод PolicyAssertionCollection.Remove находит, возвращает и удаляет утверждение на одном шаге.

  3. Измените стек привязки или контракт, добавив необходимый пользовательский BindingElement объект в BindingElements свойство или изменив PolicyConversionContext.Contract свойство.

Шаг 2 важен. После вызова всех импортеров политик WCF проверяет наличие оставшихся утверждений политики. Если существует, WCF предполагает, что импорт политики был неудачным и не импортирует связанную привязку.

Это важно

Поставщик вредоносных метаданных может попытаться отправить неправильный XML-код как часть метаданных в попытке использовать импорт политик. Настоятельно рекомендуется, чтобы пользовательские средства импорта политик были надежными для всех форм XML, которые можно передать в него.

Пользовательские MetadataImporter реализации должны реализовать собственный PolicyConversionContext объект для извлечения утверждений политики, присоединенных к пользовательскому формату метаданных.

Если вы хотите экспортировать и импортировать пользовательские элементы WSDL, которые не являются утверждениями политики, см System.ServiceModel.Description.IWsdlExportExtension . и System.ServiceModel.Description.IWsdlImportExtension.

Замечание

С помощью средства служебной программы метаданных ServiceModel (Svcutil.exe) можно использовать пользовательские средства импорта политик и экспортеров, используя те же элементы конфигурации в файле конфигурации и /svcutilConfig:<configFile> параметр.

Методы

Имя Описание
ImportPolicy(MetadataImporter, PolicyConversionContext)

Определяет метод, который может импортировать утверждения настраиваемой политики и добавить реализацию элементов привязки.

Применяется к