IPolicyImportExtension.ImportPolicy Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Определяет метод, который может импортировать утверждения настраиваемой политики и добавить реализацию элементов привязки.
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)
Параметры
- importer
- MetadataImporter
Используемый MetadataImporter объект.
- context
- PolicyConversionContext
Он PolicyConversionContext содержит утверждения политики, которые можно импортировать и коллекции элементов привязки, к которым можно добавить элементы привязки.
Примеры
В следующем примере кода показано использование 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"))
Комментарии
ImportPolicy Реализуйте метод для получения утверждений политики и выполнения некоторых изменений импортированного контракта или привязки для поддержки утверждения. Как правило, импортер политик реагирует на поиск утверждения пользовательской политики путем настройки или вставки элемента привязки в импортируемую привязку.
Windows Communication Foundation (WCF) передает два объекта методу ImportPolicy , a MetadataImporter и a PolicyConversionContext. Обычно PolicyConversionContext объект уже содержит утверждения политики для каждой области привязки.
Реализация IPolicyImportExtension выполняет следующие действия.
Находит утверждение настраиваемой политики, для которого она отвечает, вызывая GetBindingAssertionsGetMessageBindingAssertionsметоды или GetOperationBindingAssertions методы в зависимости от области.
Удаляет утверждение политики из коллекции утверждений. Метод PolicyAssertionCollection.Remove находит, возвращает и удаляет утверждение на одном шаге.
Изменяет стек привязки или контракт путем добавления необходимого пользовательского BindingElement в BindingElements свойство или изменения PolicyConversionContext.Contract свойства.
Шаг 2 важен. После вызова всех импортеров политик WCF проверяет наличие оставшихся утверждений политики. Если существует, WCF предполагает, что импорт политики был неудачным и не импортирует связанную привязку.