IPolicyExportExtension Интерфейс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Реализуйте для IPolicyExportExtension вставки утверждений настраиваемой политики привязки в сведениях языка описания веб-служб (WSDL).
public interface class IPolicyExportExtension
public interface IPolicyExportExtension
type IPolicyExportExtension = interface
Public Interface IPolicyExportExtension
- Производный
Примеры
В следующем примере кода показана IPolicyExportExtension реализация для объекта BindingElement. В этом примере настраиваемый элемент привязки присоединен к WSDL-файлу на уровне привязки.
#region IPolicyExporter Members
public void ExportPolicy(MetadataExporter exporter, PolicyConversionContext policyContext)
{
if (exporter == null)
throw new NullReferenceException("The MetadataExporter object passed to the ExporterBindingElement is null.");
if (policyContext == null)
throw new NullReferenceException("The PolicyConversionContext object passed to the ExporterBindingElement is null.");
XmlElement elem = doc.CreateElement(name1, ns1);
elem.InnerText = "My custom text.";
XmlAttribute att = doc.CreateAttribute("MyCustomAttribute", ns1);
att.Value = "ExampleValue";
elem.Attributes.Append(att);
XmlElement subElement = doc.CreateElement("MyCustomSubElement", ns1);
subElement.InnerText = "Custom Subelement Text.";
elem.AppendChild(subElement);
policyContext.GetBindingAssertions().Add(elem);
Console.WriteLine("The custom policy exporter was called.");
}
#endregion
#Region "IPolicyExporter Members"
Public Sub ExportPolicy(ByVal exporter As MetadataExporter, ByVal policyContext As PolicyConversionContext) Implements IPolicyExportExtension.ExportPolicy
If exporter Is Nothing Then
Throw New NullReferenceException("The MetadataExporter object passed to the ExporterBindingElement is null.")
End If
If policyContext Is Nothing Then
Throw New NullReferenceException("The PolicyConversionContext object passed to the ExporterBindingElement is null.")
End If
Dim elem As XmlElement = doc.CreateElement(name1, ns1)
elem.InnerText = "My custom text."
Dim att As XmlAttribute = doc.CreateAttribute("MyCustomAttribute", ns1)
att.Value = "ExampleValue"
elem.Attributes.Append(att)
Dim subElement As XmlElement = doc.CreateElement("MyCustomSubElement", ns1)
subElement.InnerText = "Custom Subelement Text."
elem.AppendChild(subElement)
policyContext.GetBindingAssertions().Add(elem)
Console.WriteLine("The custom policy exporter was called.")
End Sub
#End Region
В следующем примере кода показана System.ServiceModel.Configuration.BindingElementExtensionElement реализация, которая позволяет предыдущему экспортеру политик загружаться из файла конфигурации приложения.
public class ExporterBindingElementConfigurationSection : BindingElementExtensionElement
{
public ExporterBindingElementConfigurationSection()
{ Console.WriteLine("Exporter configuration section created."); }
public override Type BindingElementType
{ get { return typeof(ExporterBindingElement); } }
protected override BindingElement CreateBindingElement()
{ return new ExporterBindingElement(); }
}
Public Class ExporterBindingElementConfigurationSection
Inherits BindingElementExtensionElement
Public Sub New()
Console.WriteLine("Exporter configuration section created.")
End Sub
Public Overrides ReadOnly Property BindingElementType() As Type
Get
Return GetType(ExporterBindingElement)
End Get
End Property
Protected Overrides Function CreateBindingElement() As BindingElement
Return New ExporterBindingElement()
End Function
End Class
В следующем примере показан файл конфигурации узла, который загружает экспортер пользовательской политики.
<system.serviceModel>
<services>
<service
name="Microsoft.WCF.Documentation.StatefulService"
behaviorConfiguration="addMetadata"
>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/StatefulService"/>
</baseAddresses>
</host>
<endpoint
address="http://localhost:8080/StatefulService"
binding="customBinding"
bindingConfiguration="exporter"
contract="Microsoft.WCF.Documentation.IStatefulService"
/>
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"
/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="addMetadata">
<serviceMetadata
httpGetEnabled="true"
httpGetUrl=""
/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<!--
Use the name attribute of the binding element as
the value of the bindingConfiguration attribute in
your endpoint.
-->
<binding name ="exporter">
<!-- Use the name attribute of your binding element extension specified below. -->
<!-- Be certain the order of your custom binding elements is correct. -->
<exporterBinding />
<reliableSession/>
<textMessageEncoding messageVersion="Default" />
<httpTransport/>
</binding>
</customBinding>
</bindings>
<extensions>
<bindingElementExtensions>
<!-- Use the add element to associate your bindingelement configuration handler and give it a name to use. -->
<add
type="Microsoft.WCF.Documentation.ExporterBindingElementConfigurationSection,PolicyExtensions"
name="exporterBinding" />
</bindingElementExtensions>
</extensions>
</system.serviceModel>
В следующем примере показано пользовательское утверждение в WSDL-файле.
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
namespaces removed here for clarity...
>
<wsp:Policy wsu:Id="CustomBinding_IStatefulService_policy">
<wsp:ExactlyOne>
<wsp:All>
<acme
b:MyCustomAttribute="ExampleValue"
xmlns="http://Microsoft/WCF/Documentation/CustomPolicyAssertions" xmlns:b="http://Microsoft/WCF/Documentation/CustomPolicyAssertions">
My custom text.
<MyCustomSubElement>Custom Subelement Text.</MyCustomSubElement>
</acme>
<wsrm:RMAssertion xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm/policy">
<wsrm:InactivityTimeout Milliseconds="600000" />
<wsrm:AcknowledgementInterval Milliseconds="200" />
</wsrm:RMAssertion>
<wsaw:UsingAddressing />
</wsp:All>
</wsp:ExactlyOne>
</wsp:Policy>
<wsdl:import namespace="http://microsoft.wcf.documentation" location="" />
Комментарии
IPolicyExportExtension Реализуйте интерфейс для System.ServiceModel.Channels.BindingElement объекта для записи инструкций о возможностях конечных точек или требованиях к данным WSDL, предоставляемым определенной конечной точкой. Обычно элемент привязки — это элемент, реализующий некоторые функции, но это не обязательно. Чтобы загрузить экспортер политики из файла конфигурации, реализуйте System.ServiceModel.Configuration.BindingElementExtensionElement объект, возвращающий объект экспортера BindingElement политики.
Экспортер политик используется Windows Communication Foundation (WCF) для использования утверждений политики для обмена данными с клиентами о наличии этого пользовательского требования привязки или возможности конечной точки.
Метод ExportPolicy принимает MetadataExporter и PolicyConversionContext объекты. GetBindingAssertions GetMessageBindingAssertionsИспользуйте методы и GetOperationBindingAssertions методы для получения коллекций утверждений политики, которые уже экспортированы в различных областях. Затем добавьте объект утверждения пользовательской политики в соответствующую коллекцию.
Свойство Contract предоставляет экспортируемую ContractDescription конечную точку. Это позволяет расширению IPolicyExportExtension правильно ограничить экспортированные утверждения политики. Например, атрибуты безопасности в коде могут добавлять поведение ContractDescription , указывающее, где должны быть добавлены утверждения политики безопасности.
Механизм IPolicyExportExtension поддерживает только экспорт утверждений политики в WSDL. Для экспорта пользовательских элементов WSDL необходимо использовать IWsdlExportExtension механизм для непосредственного изменения WSDL.
После присоединения утверждений пользовательской политики к данным WSDL клиенты могут обнаруживать и импортировать утверждения пользовательской IPolicyImportExtension привязки с помощью объекта.
Методы
| Имя | Описание |
|---|---|
| ExportPolicy(MetadataExporter, PolicyConversionContext) |
Реализуйте для включения для экспорта утверждения настраиваемой политики о привязках. |