Sdílet prostřednictvím


Postupy: Vytvoření základní webové služby HTTP WCF

Windows Communication Foundation (WCF) umožňuje vytvořit službu, která zveřejňuje webový koncový bod. Webové koncové body odesílají data pomocí XML nebo JSON, obálka SOAP neexistuje. Toto téma ukazuje, jak takový koncový bod zveřejnit.

Poznámka:

Jediným způsobem, jak zabezpečit webový koncový bod, je zveřejnit ho prostřednictvím protokolu HTTPS pomocí zabezpečení přenosu. Při použití zabezpečení založeného na zprávách se informace o zabezpečení obvykle umístí do hlaviček PROTOKOLU SOAP a protože zprávy odeslané do koncových bodů bez protokolu SOAP neobsahují obálku SOAP, není nikde možné umístit informace o zabezpečení a musíte se spoléhat na zabezpečení přenosu.

Vytvoření webového koncového bodu

  1. Definujte kontrakt služby pomocí rozhraní označeného pomocí ServiceContractAttributeWebInvokeAttributeWebGetAttribute a atributů.

    [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
    
    

    Poznámka:

    Ve výchozím nastavení WebInvokeAttribute mapuje volání POST na operaci. Můžete však zadat metodu HTTP (například HEAD, PUT nebo DELETE) pro mapování na operaci zadáním parametru "method=". WebGetAttribute nemá parametr "method=" a mapuje pouze volání GET na operaci služby.

  2. Implementujte kontrakt služby.

    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
    

Hostování služby

  1. Vytvoření objektu WebServiceHost

    WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/"));
    
    Dim host As WebServiceHost = New WebServiceHost(GetType(Service), New Uri("http://localhost:8000/"))
    
  2. Přidejte s příponou ServiceEndpointWebHttpBehavior.

    ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
    
    Dim ep As ServiceEndpoint = host.AddServiceEndpoint(GetType(IService), New WebHttpBinding(), "")
    

    Poznámka:

    Pokud koncový bod nepřidáte, WebServiceHost automaticky se vytvoří výchozí koncový bod. WebServiceHost také přidá WebHttpBehavior a zakáže stránku nápovědy HTTP a funkci WSDL (Web Services Description Language) GET, aby koncový bod metadat nenarušoval výchozí koncový bod HTTP.

    Přidání koncového bodu bez protokolu SOAP s adresou URL "" způsobí neočekávané chování při pokusu o volání operace v koncovém bodu. Důvodem je identifikátor URI naslouchání koncového bodu, který je stejný jako identifikátor URI pro stránku nápovědy (stránka, která se zobrazí při přechodu na základní adresu služby WCF).

    Můžete udělat jednu z následujících akcí, abyste tomu zabránili:

    • Vždy zadejte neprázdný identifikátor URI pro koncový bod bez protokolu SOAP.
    • Vypněte stránku nápovědy. Můžete to udělat pomocí následujícího kódu:
    ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
    sdb.HttpHelpPageEnabled = false;
    
    Dim sdb As ServiceDebugBehavior = host.Description.Behaviors.Find(Of ServiceDebugBehavior)()
    sdb.HttpHelpPageEnabled = False
    
  3. Otevřete hostitele služby a počkejte, až uživatel stiskne klávesu ENTER.

    host.Open();
    Console.WriteLine("Service is running");
    Console.WriteLine("Press enter to quit...");
    Console.ReadLine();
    host.Close();
    
    host.Open()
    Console.WriteLine("Service is running")
    Console.WriteLine("Press enter to quit...")
    Console.ReadLine()
    host.Close()
    

    Tato ukázka ukazuje, jak hostovat službu webového stylu pomocí konzolové aplikace. Takovou službu můžete také hostovat ve službě IIS. Chcete-li to provést, zadejte WebServiceHostFactory třídu v souboru .svc, jak ukazuje následující kód.

    <%ServiceHost
        language=c#
        Debug="true"
        Service="Microsoft.Samples.Service"
        Factory=System.ServiceModel.Activation.WebServiceHostFactory%>
    

Volání operací služby namapovaných na GET v prohlížeči

  1. Otevřete webový prohlížeč, zadejte adresu URL ahttp://localhost:8000/EchoWithGet?s=Hello, world! stiskněte Enter. Adresa URL obsahuje základní adresu služby (http://localhost:8000/), relativní adresu koncového bodu (""), operaci služby pro volání ("EchoWithGet") a otazník následovaný seznamem pojmenovaných parametrů oddělených ampersandem (&).

Volání operací služby v kódu

  1. Vytvořte instanci ChannelFactory<TChannel> v rámci using bloku.

    using (ChannelFactory<IService> cf = new ChannelFactory<IService>(new WebHttpBinding(), "http://localhost:8000"))
    
    Using cf As New ChannelFactory(Of IService)(New WebHttpBinding(), "http://localhost:8000")
    
  2. Přidejte WebHttpBehavior do koncového bodu ChannelFactory<TChannel> volání.

    cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
    
    cf.Endpoint.Behaviors.Add(New WebHttpBehavior())
    
  3. Vytvořte kanál a zavolejte službu.

    IService channel = cf.CreateChannel();
    
    string s;
    
    Console.WriteLine("Calling EchoWithGet via 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/EchoWithGet?s=Hello, world!");
    Console.WriteLine("in a web browser while this sample is running.");
    
    Console.WriteLine("");
    
    Console.WriteLine("Calling EchoWithPost via HTTP POST: ");
    s = channel.EchoWithPost("Hello, world");
    Console.WriteLine("   Output: {0}", s);
    
    Dim channel As IService = cf.CreateChannel()
    
    Dim s As String
    
    Console.WriteLine("Calling EchoWithGet via 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/EchoWithGet?s=Hello, world!")
    Console.WriteLine("in a web browser while this sample is running.")
    
    Console.WriteLine("")
    
    Console.WriteLine("Calling EchoWithPost via HTTP POST: ")
    s = channel.EchoWithPost("Hello, world")
    Console.WriteLine("   Output: {0}", s)
    
  4. Zavřete tlačítko WebServiceHost.

    host.Close();
    
    host.Close()
    

Příklad

Následuje úplný výpis kódu pro tento příklad.

// Service.cs
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)
        {
            WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/"));
            try
            {
                ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
                host.Open();
                using (ChannelFactory<IService> cf = new ChannelFactory<IService>(new WebHttpBinding(), "http://localhost:8000"))
                {
                    cf.Endpoint.Behaviors.Add(new WebHttpBehavior());

                    IService channel = cf.CreateChannel();

                    string s;

                    Console.WriteLine("Calling EchoWithGet via 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/EchoWithGet?s=Hello, world!");
                    Console.WriteLine("in a web browser while this sample is running.");

                    Console.WriteLine("");

                    Console.WriteLine("Calling EchoWithPost via HTTP POST: ");
                    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();
            }
        }
    }
}

'Service.cs
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 WebServiceHost = New WebServiceHost(GetType(Service), New Uri("http://localhost:8000/"))
        Try
            Dim ep As ServiceEndpoint = host.AddServiceEndpoint(GetType(IService), New WebHttpBinding(), "")
            host.Open()
            Using cf As New ChannelFactory(Of IService)(New WebHttpBinding(), "http://localhost:8000")

                cf.Endpoint.Behaviors.Add(New WebHttpBehavior())

                Dim channel As IService = cf.CreateChannel()

                Dim s As String

                Console.WriteLine("Calling EchoWithGet via 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/EchoWithGet?s=Hello, world!")
                Console.WriteLine("in a web browser while this sample is running.")

                Console.WriteLine("")

                Console.WriteLine("Calling EchoWithPost via HTTP POST: ")
                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

Zkompilování kódu

Při kompilaci Service.cs odkazu System.ServiceModel.dll a System.ServiceModel.Web.dll.

Viz také