Aracılığıyla paylaş


Nasıl yapılır: Kod Kullanarak Bir Hizmet için Meta Verileri Yayımlama

Bu, Windows Communication Foundation (WCF) hizmetinin meta verilerini yayımlamayı ele alan iki nasıl yapılır konusundan biridir. Yapılandırma dosyası ve kod kullanarak hizmetin meta verileri nasıl yayımlaması gerektiğini belirtmenin iki yolu vardır. Bu konu başlığında, bir hizmet için kod kullanarak meta verilerin nasıl yayımlanması gösterilmektedir.

Dikkat

Bu konu başlığında, meta verilerin güvenli olmayan bir şekilde nasıl yayımlanması gösterilmektedir. Herhangi bir istemci hizmetten meta verileri alabilir. Hizmetinizin meta verileri güvenli bir şekilde yayımlamasını istiyorsanız. Bkz. Özel Güvenli Meta Veri Uç Noktası.

Yapılandırma dosyasında meta verileri yayımlama hakkında daha fazla bilgi için bkz . Nasıl yapılır: Yapılandırma Dosyası Kullanarak Hizmet için Meta Verileri Yayımlama. Meta verileri yayımlama, istemcilerin sorgu dizesini kullanarak WS-Transfer GET isteği veya HTTP/GET isteği kullanarak ?wsdl meta verileri almasını sağlar. Kodun çalıştığından emin olmak için temel bir WCF hizmeti oluşturmanız gerekir. Aşağıdaki kodda temel bir şirket içinde barındırılan hizmet sağlanır.

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

Kodda meta verileri yayımlamak için

  1. Konsol uygulamasının ana yönteminde, hizmet türünü ve temel adresi geçirerek bir ServiceHost nesne örneği oluşturun.

    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. 1. adım için kodun hemen altında bir deneme bloğu oluşturun; bu, hizmet çalışırken oluşan özel durumları yakalar.

    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. Hizmet ana bilgisayarının zaten bir ServiceMetadataBehavioröğesini içerip içermediğini denetleyin, değilse yeni ServiceMetadataBehavior bir örnek oluşturun.

    // 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. özelliğini şu şekilde ayarlayın:HttpGetEnabledtrue.

    smb.HttpGetEnabled = true;
    
    smb.HttpGetEnabled = True
    
  5. bir ServiceMetadataBehaviorMetadataExporter özellik içerir. bir MetadataExporterPolicyVersion özellik içerir. özelliğinin PolicyVersion değerini olarak Policy15ayarlayın. PolicyVersion özelliği olarak da ayarlanabilirPolicy12. Meta veri dışarı aktarıcısı Policy15 olarak ayarlandığında, "WS-policy 1.5 ile uyumlu olan meta verilerle ilke bilgileri oluşturur. Meta veri dışarı aktarıcısı Policy12 olarak ayarlandığında, WS-policy 1.2'ye uygun ilke bilgileri oluşturur.

    smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
    
    smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15
    
  6. ServiceMetadataBehavior Örneği hizmet konağı davranış koleksiyonuna ekleyin.

    svcHost.Description.Behaviors.Add(smb);
    
    svcHost.Description.Behaviors.Add(smb)
    
  7. Meta veri değişim uç noktasını hizmet konağına ekleyin.

    // Add MEX endpoint
    svcHost.AddServiceEndpoint(
      ServiceMetadataBehavior.MexContractName,
      MetadataExchangeBindings.CreateMexHttpBinding(),
      "mex"
    );
    
    'Add MEX endpoint
    svcHost.AddServiceEndpoint( _
          ServiceMetadataBehavior.MexContractName, _
          MetadataExchangeBindings.CreateMexHttpBinding(), _
          "mex")
    
  8. Hizmet konağına bir uygulama uç noktası ekleyin.

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

    Not

    Hizmete herhangi bir uç nokta eklemezseniz, çalışma zamanı sizin için varsayılan uç noktaları ekler. Bu örnekte, hizmet olarak ayarlandığındantrue, hizmet ServiceMetadataBehavior yayımlama meta verilerini etkinleştirmiştir. Varsayılan uç noktalar hakkında daha fazla bilgi için bkz. WCF Hizmetleri için Basitleştirilmiş Yapılandırma ve Basitleştirilmiş Yapılandırma.

  9. Hizmet ana bilgisayarını açın ve gelen aramaları bekleyin. Kullanıcı ENTER tuşuna bastığında hizmet ana bilgisayarını kapatın.

    // 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. Konsol uygulamasını derleyin ve çalıştırın.

  11. Hizmetinhttp://localhost:8001/MetadataSample temel adresine (bu örnekte) göz atın ve meta veri yayımlamanın açık olduğunu doğrulayın. Üst kısımda ve hemen altında "Hizmet oluşturdunuz" ifadesinin altında "Basit Hizmet" yazan bir Web sayfası görüntüleniyor olmalıdır. Aksi takdirde, sonuçta elde edilen sayfanın üst kısmındaki bir ileti görüntülenir: "Bu hizmet için meta veri yayımlama şu anda devre dışı."

Örnek

Aşağıdaki kod örneği, kodda hizmet için meta verileri yayımlayan temel bir WCF hizmetinin uygulamasını gösterir.

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

Ayrıca bkz.