Udostępnij za pośrednictwem


Instrukcje: Publikowanie metadanych dla usługi przy użyciu kodu

Jest to jeden z dwóch tematów z instrukcjami, które omawiają publikowanie metadanych dla usługi Windows Communication Foundation (WCF). Istnieją dwa sposoby określania sposobu publikowania metadanych przez usługę przy użyciu pliku konfiguracji i używania kodu. W tym temacie przedstawiono sposób publikowania metadanych dla usługi przy użyciu kodu.

Uwaga

W tym temacie przedstawiono sposób publikowania metadanych w sposób niezabezpieczony. Każdy klient może pobrać metadane z usługi. Jeśli chcesz, aby usługa publikowała metadane w bezpieczny sposób. zobacz Niestandardowy bezpieczny punkt końcowy metadanych.

Aby uzyskać więcej informacji na temat publikowania metadanych w pliku konfiguracji, zobacz How to: Publish Metadata for a Service Using a Configuration File (Instrukcje: publikowanie metadanych dla usługi przy użyciu pliku konfiguracji). Metadane publikowania umożliwiają klientom pobieranie metadanych przy użyciu żądania GET WS-Transfer lub żądania HTTP/GET przy użyciu ?wsdl ciągu zapytania. Aby upewnić się, że kod działa, musisz utworzyć podstawową usługę WCF. Podstawowa samoobsługa jest udostępniana w poniższym kodzie.

using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace Metadata.Samples
{
    [ServiceContract]
    public interface ISimpleService
    {
        [OperationContract]
        string SimpleMethod(string msg);
    }

    class SimpleService : ISimpleService
    {
        public string SimpleMethod(string msg)
        {
            Console.WriteLine("The caller passed in " + msg);
            return "Hello " + msg;
        }
    }
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.ServiceModel.Description

<ServiceContract()> _
Public Interface ISimpleService
    <OperationContract()> _
    Function SimpleMethod(ByVal msg As String) As String
End Interface

Class SimpleService
    Implements ISimpleService

    Public Function SimpleMethod(ByVal msg As String) As String Implements ISimpleService.SimpleMethod
        Console.WriteLine("The caller passed in " + msg)
        Return "Hello " + msg
    End Function
End Class

Aby opublikować metadane w kodzie

  1. W ramach głównej metody aplikacji konsolowej utwórz wystąpienie ServiceHost obiektu, przekazując typ usługi i adres podstawowy.

    ServiceHost svcHost = new ServiceHost(typeof(SimpleService), new Uri("http://localhost:8001/MetadataSample"));
    
    Dim svcHost As New ServiceHost(GetType(SimpleService), New Uri("http://localhost:8001/MetadataSample"))
    
  2. Utwórz blok try bezpośrednio poniżej kodu dla kroku 1. Spowoduje to przechwycenie wszelkich wyjątków zgłaszanych podczas działania usługi.

    try
    {
    
    Try
    
    }
    catch (CommunicationException commProblem)
    {
        Console.WriteLine("There was a communication problem. " + commProblem.Message);
        Console.Read();
    }
    
    Catch commProblem As CommunicationException
    
        Console.WriteLine("There was a communication problem. " + commProblem.Message)
        Console.Read()
    End Try
    
  3. Sprawdź, czy host usługi zawiera ServiceMetadataBehaviorjuż element , jeśli nie, utwórz nowe ServiceMetadataBehavior wystąpienie.

    // Check to see if the service host already has a ServiceMetadataBehavior
    ServiceMetadataBehavior smb = svcHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
    // If not, add one
    if (smb == null)
        smb = new ServiceMetadataBehavior();
    
    'Check to see if the service host already has a ServiceMetadataBehavior
    Dim smb As ServiceMetadataBehavior = svcHost.Description.Behaviors.Find(Of ServiceMetadataBehavior)()
    'If not, add one
    If (smb Is Nothing) Then
        smb = New ServiceMetadataBehavior()
    End If
    
  4. HttpGetEnabled Ustaw właściwość natrue.

    smb.HttpGetEnabled = true;
    
    smb.HttpGetEnabled = True
    
  5. Obiekt ServiceMetadataBehavior zawiera MetadataExporter właściwość . Obiekt MetadataExporter zawiera PolicyVersion właściwość . Ustaw wartość PolicyVersion właściwości na Policy15. Właściwość PolicyVersion można również ustawić na Policy12. Po ustawieniu Policy15 na eksporter metadanych są generowane informacje o zasadach z metadanymi zgodnymi z usługą WS-Policy 1.5. Po ustawieniu Policy12 na eksporter metadanych są generowane informacje o zasadach zgodne z usługą WS-Policy 1.2.

    smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
    
    smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15
    
  6. ServiceMetadataBehavior Dodaj wystąpienie do kolekcji zachowań hosta usługi.

    svcHost.Description.Behaviors.Add(smb);
    
    svcHost.Description.Behaviors.Add(smb)
    
  7. Dodaj punkt końcowy wymiany metadanych do hosta usługi.

    // Add MEX endpoint
    svcHost.AddServiceEndpoint(
      ServiceMetadataBehavior.MexContractName,
      MetadataExchangeBindings.CreateMexHttpBinding(),
      "mex"
    );
    
    'Add MEX endpoint
    svcHost.AddServiceEndpoint( _
          ServiceMetadataBehavior.MexContractName, _
          MetadataExchangeBindings.CreateMexHttpBinding(), _
          "mex")
    
  8. Dodaj punkt końcowy aplikacji do hosta usługi.

    // Add application endpoint
    svcHost.AddServiceEndpoint(typeof(ISimpleService), new WSHttpBinding(), "");
    
    'Add application endpoint
    svcHost.AddServiceEndpoint(GetType(ISimpleService), New WSHttpBinding(), "")
    

    Uwaga

    Jeśli nie dodasz żadnych punktów końcowych do usługi, środowisko uruchomieniowe doda domyślne punkty końcowe. W tym przykładzie, ponieważ usługa ma ustawioną ServiceMetadataBehavior wartość true, usługa ma włączone metadane publikowania. Aby uzyskać więcej informacji na temat domyślnych punktów końcowych, zobacz Uproszczona konfiguracja i Uproszczona konfiguracja dla usług WCF.

  9. Otwórz hosta usługi i poczekaj na połączenia przychodzące. Gdy użytkownik naciśnie klawisz ENTER, zamknij hosta usługi.

    // Open the service host to accept incoming calls
    svcHost.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.
    svcHost.Close();
    
    'Open the service host to accept incoming calls
    svcHost.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.
    svcHost.Close()
    
  10. Skompiluj i uruchom aplikację konsolową.

  11. Przejdź do podstawowego adresu usługi (http://localhost:8001/MetadataSample w tym przykładzie) i sprawdź, czy publikowanie metadanych jest włączone. Powinna zostać wyświetlona strona sieci Web z napisem "Simple Service" u góry i bezpośrednio poniżej "Utworzono usługę". Jeśli nie, w górnej części wynikowej strony zostanie wyświetlony komunikat: "Publikowanie metadanych dla tej usługi jest obecnie wyłączone".

Przykład

Poniższy przykład kodu przedstawia implementację podstawowej usługi WCF, która publikuje metadane dla usługi w kodzie.

using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace Metadata.Samples
{
    [ServiceContract]
    public interface ISimpleService
    {
        [OperationContract]
        string SimpleMethod(string msg);
    }

    class SimpleService : ISimpleService
    {
        public string SimpleMethod(string msg)
        {
            Console.WriteLine("The caller passed in " + msg);
            return "Hello " + msg;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost svcHost = new ServiceHost(typeof(SimpleService), new Uri("http://localhost:8001/MetadataSample"));
            try
            {
                // Check to see if the service host already has a ServiceMetadataBehavior
                ServiceMetadataBehavior smb = svcHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
                // If not, add one
                if (smb == null)
                    smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                svcHost.Description.Behaviors.Add(smb);
                // Add MEX endpoint
                svcHost.AddServiceEndpoint(
                  ServiceMetadataBehavior.MexContractName,
                  MetadataExchangeBindings.CreateMexHttpBinding(),
                  "mex"
                );
                // Add application endpoint
                svcHost.AddServiceEndpoint(typeof(ISimpleService), new WSHttpBinding(), "");
                // Open the service host to accept incoming calls
                svcHost.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.
                svcHost.Close();
            }
            catch (CommunicationException commProblem)
            {
                Console.WriteLine("There was a communication problem. " + commProblem.Message);
                Console.Read();
            }
        }
    }
}
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.ServiceModel.Description

<ServiceContract()> _
Public Interface ISimpleService
    <OperationContract()> _
    Function SimpleMethod(ByVal msg As String) As String
End Interface

Class SimpleService
    Implements ISimpleService

    Public Function SimpleMethod(ByVal msg As String) As String Implements ISimpleService.SimpleMethod
        Console.WriteLine("The caller passed in " + msg)
        Return "Hello " + msg
    End Function
End Class

Module Module1

    Sub Main()
        Dim svcHost As New ServiceHost(GetType(SimpleService), New Uri("http://localhost:8001/MetadataSample"))
        Try
            'Check to see if the service host already has a ServiceMetadataBehavior
            Dim smb As ServiceMetadataBehavior = svcHost.Description.Behaviors.Find(Of ServiceMetadataBehavior)()
            'If not, add one
            If (smb Is Nothing) Then
                smb = New ServiceMetadataBehavior()
            End If
            smb.HttpGetEnabled = True
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15
            svcHost.Description.Behaviors.Add(smb)
            'Add MEX endpoint
            svcHost.AddServiceEndpoint( _
                  ServiceMetadataBehavior.MexContractName, _
                  MetadataExchangeBindings.CreateMexHttpBinding(), _
                  "mex")
            'Add application endpoint
            svcHost.AddServiceEndpoint(GetType(ISimpleService), New WSHttpBinding(), "")
            'Open the service host to accept incoming calls
            svcHost.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.
            svcHost.Close()
        Catch commProblem As CommunicationException

            Console.WriteLine("There was a communication problem. " + commProblem.Message)
            Console.Read()
        End Try
    End Sub
End Module

Zobacz też