Nasıl yapılır: Bir Sözleşmeyi SOAP ve Web İstemcilerine Sunma

Varsayılan olarak, Windows Communication Foundation (WCF) uç noktaları yalnızca SOAP istemcileri için kullanılabilir hale getirir. Nasıl yapılır: Temel WCF Web HTTP Hizmeti Oluşturma bölümünde, SOAP olmayan istemciler için bir uç nokta kullanıma sunulmuştur. Aynı sözleşmeyi web uç noktası ve SOAP uç noktası olarak her iki yolla da kullanılabilir hale getirmek istediğiniz zamanlar olabilir. Bu konuda bunun nasıl yapıldığını gösteren bir örnek gösterilmektedir.

Hizmet sözleşmesini tanımlamak için

  1. Aşağıdaki kodda gösterildiği gibi , ServiceContractAttributeWebInvokeAttribute ve WebGetAttribute öznitelikleriyle işaretlenmiş bir arabirim kullanarak bir hizmet sözleşmesi tanımlayın:

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebGet]
        string EchoWithGet(string s);
    
        [OperationContract]
        [WebInvoke]
        string EchoWithPost(string s);
    }
    
    <ServiceContract()> _
    Public Interface IService
    
        <OperationContract()> _
        <WebGet()> _
        Function EchoWithGet(ByVal s As String) As String
    
        <OperationContract()> _
        <WebInvoke()> _
        Function EchoWithPost(ByVal s As String) As String
    End Interface
    

    Not

    Varsayılan olarak WebInvokeAttribute POST çağrılarını işleme eşler. Ancak bir "method=" parametresi belirterek işlemle eşlenecek yöntemi belirtebilirsiniz. WebGetAttribute bir "method=" parametresine sahip değildir ve yalnızca GET çağrılarını hizmet işlemine eşler.

  2. Aşağıdaki kodda gösterildiği gibi hizmet sözleşmesini uygulayın:

    public class Service : IService
    {
        public string EchoWithGet(string s)
        {
            return "You said " + s;
        }
    
        public string EchoWithPost(string s)
        {
            return "You said " + s;
        }
    }
    
    Public Class Service
        Implements IService
        Public Function EchoWithGet(ByVal s As String) As String Implements IService.EchoWithGet
            Return "You said " + s
        End Function
    
        Public Function EchoWithPost(ByVal s As String) As String Implements IService.EchoWithPost
            Return "You said " + s
        End Function
    End Class
    

Hizmeti barındırmak için

  1. Aşağıdaki kodda gösterildiği gibi bir ServiceHost nesne oluşturun:

    ServiceHost host = new ServiceHost(typeof(Service), new Uri("http://localhost:8000"));
    
    Dim host As New ServiceHost(GetType(Service), New Uri("http://localhost:8000"))
    
  2. ServiceEndpoint Aşağıdaki kodda gösterildiği gibi SOAP uç noktası için ile BasicHttpBinding ekleyin:

    host.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "Soap");
    
    host.AddServiceEndpoint(GetType(IService), New BasicHttpBinding(), "Soap")
    
  3. ServiceEndpoint AŞAĞıDAKI kodda gösterildiği gibi SOAP olmayan uç nokta için ile WebHttpBinding ekleyin ve uç noktaya ekleyinWebHttpBehavior:

    ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "Web");
    endpoint.Behaviors.Add(new WebHttpBehavior());
    
    Dim endpoint As ServiceEndpoint
    endpoint = host.AddServiceEndpoint(GetType(IService), New WebHttpBinding(), "Web")
    endpoint.Behaviors.Add(New WebHttpBehavior())
    
  4. Aşağıdaki kodda gösterildiği gibi hizmet ana bilgisayarını açmak için bir ServiceHost örnekte çağrısı Open() yapın:

    host.Open();
    
    host.Open()
    

Tarayıcıda GET ile eşlenmiş hizmet işlemlerini çağırmak için

  1. Bir web tarayıcısında "http://localhost:8000/Web/EchoWithGet?s=Hello, world!" konumuna gidin. URL hizmetinhttp://localhost:8000/ (), uç noktanın göreli adresini (""), çağrılacak hizmet işlemini ("EchoWithGet") ve bir soru işaretini ve ardından bir ve işaretiyle (&) ayrılmış adlandırılmış parametrelerin listesini içerir.

Kodda Web uç noktasında hizmet işlemlerini çağırmak için

  1. Aşağıdaki kodda gösterildiği gibi bir using bloğun içinde örneğini WebChannelFactory<TChannel> oluşturun.

    using (WebChannelFactory<IService> wcf = new WebChannelFactory<IService>(new Uri("http://localhost:8000/Web")))
    
    Using wcf As New WebChannelFactory(Of IService)(New Uri("http://localhost:8000/Web"))
    

Not

Close() , bloğun sonundaki kanalda otomatik olarak çağrılır using .

  1. Aşağıdaki kodda gösterildiği gibi kanalı oluşturun ve hizmeti çağırın.

    IService channel = wcf.CreateChannel();
    
    string s;
    
    Console.WriteLine("Calling EchoWithGet by HTTP GET: ");
    s = channel.EchoWithGet("Hello, world");
    Console.WriteLine("   Output: {0}", s);
    
    Console.WriteLine("");
    Console.WriteLine("This can also be accomplished by navigating to");
    Console.WriteLine("http://localhost:8000/Web/EchoWithGet?s=Hello, world!");
    Console.WriteLine("in a web browser while this sample is running.");
    
    Console.WriteLine("");
    
    Console.WriteLine("Calling EchoWithPost by HTTP POST: ");
    s = channel.EchoWithPost("Hello, world");
    Console.WriteLine("   Output: {0}", s);
    
    Dim channel As IService = wcf.CreateChannel()
    
    Dim s As String
    
    Console.WriteLine("Calling EchoWithGet by HTTP GET: ")
    s = channel.EchoWithGet("Hello, world")
    Console.WriteLine("   Output:  {0}", s)
    
    Console.WriteLine("")
    Console.WriteLine("This can also be accomplished by navigating to")
    Console.WriteLine("http://localhost:8000/Web/EchoWithGet?s=Hello, world!")
    Console.WriteLine("in a web browser while this sample is running.")
    
    Console.WriteLine("")
    
    Console.WriteLine("Calling EchoWithPost by HTTP POST: ")
    s = channel.EchoWithPost("Hello, world")
    Console.WriteLine("   Output:  {0}", s)
    

SOAP uç noktasında hizmet işlemlerini çağırmak için

  1. Aşağıdaki kodda gösterildiği gibi bir using bloğun içinde örneğini ChannelFactory oluşturun.

    using (ChannelFactory<IService> scf = new ChannelFactory<IService>(new BasicHttpBinding(), "http://localhost:8000/Soap"))
    
    Using scf As New ChannelFactory(Of IService)(New BasicHttpBinding(), "http://localhost:8000/Soap")
    
  2. Aşağıdaki kodda gösterildiği gibi kanalı oluşturun ve hizmeti çağırın.

    IService channel = scf.CreateChannel();
    
    string s;
    
    Console.WriteLine("Calling EchoWithGet on SOAP endpoint: ");
    s = channel.EchoWithGet("Hello, world");
    Console.WriteLine("   Output: {0}", s);
    
    Console.WriteLine("");
    
    Console.WriteLine("Calling EchoWithPost on SOAP endpoint: ");
    s = channel.EchoWithPost("Hello, world");
    Console.WriteLine("   Output: {0}", s);
    
    Dim channel As IService = scf.CreateChannel()
    
    Dim s As String
    
    Console.WriteLine("Calling EchoWithGet on SOAP endpoint: ")
    s = channel.EchoWithGet("Hello, world")
    Console.WriteLine("   Output:  {0}", s)
    
    Console.WriteLine("")
    
    Console.WriteLine("Calling EchoWithPost on SOAP endpoint: ")
    s = channel.EchoWithPost("Hello, world")
    Console.WriteLine("   Output:  {0}", s)
    

Hizmet ana bilgisayarını kapatmak için

  1. Aşağıdaki kodda gösterildiği gibi hizmet ana bilgisayarını kapatın.

    host.Close();
    
    host.Close()
    

Örnek

Bu konunun tam kod listesi aşağıdadır:

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Text;

namespace Microsoft.ServiceModel.Samples.BasicWebProgramming
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebGet]
        string EchoWithGet(string s);

        [OperationContract]
        [WebInvoke]
        string EchoWithPost(string s);
    }

    public class Service : IService
    {
        public string EchoWithGet(string s)
        {
            return "You said " + s;
        }

        public string EchoWithPost(string s)
        {
            return "You said " + s;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(Service), new Uri("http://localhost:8000"));
            host.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "Soap");
            ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "Web");
            endpoint.Behaviors.Add(new WebHttpBehavior());

            try
            {
                host.Open();

                using (WebChannelFactory<IService> wcf = new WebChannelFactory<IService>(new Uri("http://localhost:8000/Web")))
                {
                    IService channel = wcf.CreateChannel();

                    string s;

                    Console.WriteLine("Calling EchoWithGet by HTTP GET: ");
                    s = channel.EchoWithGet("Hello, world");
                    Console.WriteLine("   Output: {0}", s);

                    Console.WriteLine("");
                    Console.WriteLine("This can also be accomplished by navigating to");
                    Console.WriteLine("http://localhost:8000/Web/EchoWithGet?s=Hello, world!");
                    Console.WriteLine("in a web browser while this sample is running.");

                    Console.WriteLine("");

                    Console.WriteLine("Calling EchoWithPost by HTTP POST: ");
                    s = channel.EchoWithPost("Hello, world");
                    Console.WriteLine("   Output: {0}", s);
                    Console.WriteLine("");
                }
                using (ChannelFactory<IService> scf = new ChannelFactory<IService>(new BasicHttpBinding(), "http://localhost:8000/Soap"))
                {
                    IService channel = scf.CreateChannel();

                    string s;

                    Console.WriteLine("Calling EchoWithGet on SOAP endpoint: ");
                    s = channel.EchoWithGet("Hello, world");
                    Console.WriteLine("   Output: {0}", s);

                    Console.WriteLine("");

                    Console.WriteLine("Calling EchoWithPost on SOAP endpoint: ");
                    s = channel.EchoWithPost("Hello, world");
                    Console.WriteLine("   Output: {0}", s);
                    Console.WriteLine("");
                }

                Console.WriteLine("Press [Enter] to terminate");
                Console.ReadLine();
                host.Close();
            }
            catch (CommunicationException cex)
            {
                Console.WriteLine("An exception occurred: {0}", cex.Message);
                host.Abort();
            }
        }
    }
}
Imports System.Collections.Generic
Imports System.ServiceModel
Imports System.ServiceModel.Description
Imports System.ServiceModel.Web
Imports System.Text

<ServiceContract()> _
Public Interface IService

    <OperationContract()> _
    <WebGet()> _
    Function EchoWithGet(ByVal s As String) As String

    <OperationContract()> _
    <WebInvoke()> _
    Function EchoWithPost(ByVal s As String) As String
End Interface

Public Class Service
    Implements IService
    Public Function EchoWithGet(ByVal s As String) As String Implements IService.EchoWithGet
        Return "You said " + s
    End Function

    Public Function EchoWithPost(ByVal s As String) As String Implements IService.EchoWithPost
        Return "You said " + s
    End Function
End Class
Module Program

    Sub Main()
        Dim host As New ServiceHost(GetType(Service), New Uri("http://localhost:8000"))
        host.AddServiceEndpoint(GetType(IService), New BasicHttpBinding(), "Soap")
        Dim endpoint As ServiceEndpoint
        endpoint = host.AddServiceEndpoint(GetType(IService), New WebHttpBinding(), "Web")
        endpoint.Behaviors.Add(New WebHttpBehavior())

        Try
            host.Open()

            Using wcf As New WebChannelFactory(Of IService)(New Uri("http://localhost:8000/Web"))

                Dim channel As IService = wcf.CreateChannel()

                Dim s As String

                Console.WriteLine("Calling EchoWithGet by HTTP GET: ")
                s = channel.EchoWithGet("Hello, world")
                Console.WriteLine("   Output:  {0}", s)

                Console.WriteLine("")
                Console.WriteLine("This can also be accomplished by navigating to")
                Console.WriteLine("http://localhost:8000/Web/EchoWithGet?s=Hello, world!")
                Console.WriteLine("in a web browser while this sample is running.")

                Console.WriteLine("")

                Console.WriteLine("Calling EchoWithPost by HTTP POST: ")
                s = channel.EchoWithPost("Hello, world")
                Console.WriteLine("   Output:  {0}", s)
                Console.WriteLine("")
            End Using
            Using scf As New ChannelFactory(Of IService)(New BasicHttpBinding(), "http://localhost:8000/Soap")

                Dim channel As IService = scf.CreateChannel()

                Dim s As String

                Console.WriteLine("Calling EchoWithGet on SOAP endpoint: ")
                s = channel.EchoWithGet("Hello, world")
                Console.WriteLine("   Output:  {0}", s)

                Console.WriteLine("")

                Console.WriteLine("Calling EchoWithPost on SOAP endpoint: ")
                s = channel.EchoWithPost("Hello, world")
                Console.WriteLine("   Output:  {0}", s)
                Console.WriteLine("")
            End Using


            Console.WriteLine("Press <Enter> to terminate")
            Console.ReadLine()
            host.Close()
        Catch cex As CommunicationException
            Console.WriteLine("An exception occurred:  {0}", cex.Message)
            host.Abort()
        End Try

    End Sub
End Module

Kod derleme

Service.cs derlerken System.ServiceModel.dll ve System.ServiceModel.Web.dll başvurun.

Ayrıca bkz.