Instrukcje: Eksportowanie niestandardowych asercji zasad

Asercji zasad opisują możliwości i wymagania punktu końcowego usługi. Aplikacje usług mogą używać niestandardowych asercji zasad w metadanych usługi do przekazywania informacji o punkcie końcowym, powiązaniu lub dostosowywaniu kontraktu do aplikacji klienckiej. Za pomocą programu Windows Communication Foundation (WCF) można eksportować asercji w wyrażeniach zasad dołączonych w powiązaniach WSDL w punkcie końcowym, operacji lub tematach komunikatów, w zależności od możliwości lub wymagań, które komunikujesz.

Niestandardowe asercji zasad są eksportowane przez zaimplementowanie interfejsu System.ServiceModel.Description.IPolicyExportExtension na obiekcie System.ServiceModel.Channels.BindingElement i wstawianie elementu powiązania bezpośrednio do powiązania punktu końcowego usługi lub przez zarejestrowanie elementu powiązania w pliku konfiguracji aplikacji. Implementacja eksportu zasad powinna dodać niestandardową asercję System.Xml.XmlElement zasad jako wystąpienie do odpowiedniego System.ServiceModel.Description.PolicyAssertionCollection elementu przekazanego ExportPolicySystem.ServiceModel.Description.PolicyConversionContext do metody .

Ponadto należy sprawdzić PolicyVersion właściwość WsdlExporter klasy i wyeksportować zagnieżdżone wyrażenia zasad i atrybuty struktury zasad w prawidłowej przestrzeni nazw na podstawie określonej wersji zasad.

Aby zaimportować niestandardowe asercji zasad, zobacz System.ServiceModel.Description.IPolicyImportExtension instrukcje i Instrukcje: importowanie asercji zasad niestandardowych.

Aby wyeksportować niestandardowe asercji zasad

  1. Zaimplementuj System.ServiceModel.Description.IPolicyExportExtension interfejs na obiekcie System.ServiceModel.Channels.BindingElement. Poniższy przykład kodu przedstawia implementację niestandardowej asercji zasad na poziomie powiązania.

    #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
    
  2. Wstaw element powiązania do powiązania punktu końcowego programowo lub przy użyciu pliku konfiguracji aplikacji. Zapoznaj się z poniższymi procedurami.

Aby wstawić element powiązania przy użyciu pliku konfiguracji aplikacji

  1. Zaimplementuj System.ServiceModel.Configuration.BindingElementExtensionElement element powiązania asercji niestandardowych zasad.

  2. Dodaj rozszerzenie elementu powiązania do pliku konfiguracji przy użyciu elementu bindingElementExtensions>.<

  3. Skompiluj powiązanie niestandardowe przy użyciu elementu System.ServiceModel.Channels.CustomBinding.

Aby wstawić element powiązania programowo

  1. Utwórz nowy System.ServiceModel.Channels.BindingElement element i dodaj go do elementu System.ServiceModel.Channels.CustomBinding.

  2. Dodaj powiązanie niestandardowe z kroku 1. do nowego punktu końcowego i dodaj do obiektu System.ServiceModel.ServiceHost ten nowy punkt końcowy usługi, wywołując metodę AddServiceEndpoint .

  3. Otwórz klasę ServiceHost. Poniższy przykład kodu przedstawia tworzenie powiązania niestandardowego i programowe wstawianie elementów powiązania.

    Uri baseAddress = new Uri("http://localhost:8000/servicemodelsamples/service");
    
    // Create a ServiceHost for the CalculatorService type and provide the base address.
    using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress))
    {
        // Create a custom binding that contains two binding elements.
        ReliableSessionBindingElement reliableSession = new ReliableSessionBindingElement();
        reliableSession.Ordered = true;
    
        HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();
        httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
        httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
    
        CustomBinding binding = new CustomBinding(reliableSession, httpTransport);
    
        // Add an endpoint using that binding.
        serviceHost.AddServiceEndpoint(typeof(ICalculator), binding, "");
    
        // Add a MEX endpoint.
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
        smb.HttpGetEnabled = true;
        smb.HttpGetUrl = new Uri("http://localhost:8001/servicemodelsamples");
        serviceHost.Description.Behaviors.Add(smb);
    
        // Open the ServiceHostBase to create listeners and start listening for messages.
        serviceHost.Open();
    
        // The service can now be accessed.
        Console.WriteLine("The service is ready.");
        Console.WriteLine("Press <ENTER> to terminate service.");
        Console.WriteLine();
        Console.ReadLine();
    
        // Close the ServiceHostBase to shutdown the service.
        serviceHost.Close();
    }
    
    Dim baseAddress As New Uri("http://localhost:8000/servicemodelsamples/service")
    
    ' Create a ServiceHost for the CalculatorService type and provide the base address.
    Using serviceHost As New ServiceHost(GetType(CalculatorService), baseAddress)
        ' Create a custom binding that contains two binding elements.
        Dim reliableSession As New ReliableSessionBindingElement()
        reliableSession.Ordered = True
    
        Dim httpTransport As New HttpTransportBindingElement()
        httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous
        httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard
    
        Dim binding As New CustomBinding(reliableSession, httpTransport)
    
        ' Add an endpoint using that binding.
        serviceHost.AddServiceEndpoint(GetType(ICalculator), binding, "")
    
        ' Add a MEX endpoint.
        Dim smb As New ServiceMetadataBehavior()
        smb.HttpGetEnabled = True
        smb.HttpGetUrl = New Uri("http://localhost:8001/servicemodelsamples")
        serviceHost.Description.Behaviors.Add(smb)
    
        ' Open the ServiceHostBase to create listeners and start listening for messages.
        serviceHost.Open()
    
        ' The service can now be accessed.
        Console.WriteLine("The service is ready.")
        Console.WriteLine("Press <ENTER> to terminate service.")
        Console.WriteLine()
        Console.ReadLine()
    
        ' Close the ServiceHostBase to shutdown the service.
        serviceHost.Close()
    End Using
    

Zobacz też