Anteckning
Åtkomst till den här sidan kräver auktorisering. Du kan prova att logga in eller ändra kataloger.
Åtkomst till den här sidan kräver auktorisering. Du kan prova att ändra kataloger.
Med Windows Communication Foundation (WCF) kan du skapa en tjänst som exponerar en webbslutpunkt. Webbslutpunkter skickar data via XML eller JSON, det finns inget SOAP-kuvert. Det här avsnittet visar hur du exponerar en sådan slutpunkt.
Kommentar
Det enda sättet att skydda en webbslutpunkt är att exponera den via HTTPS med hjälp av transportsäkerhet. När du använder meddelandebaserad säkerhet placeras säkerhetsinformation vanligtvis i SOAP-huvuden och eftersom meddelanden som skickas till icke-SOAP-slutpunkter inte innehåller något SOAP-kuvert finns det ingenstans att placera säkerhetsinformationen och du måste förlita dig på transportsäkerhet.
Skapa en webbslutpunkt
Definiera ett tjänstkontrakt med hjälp av ett gränssnitt som har markerats med attributen ServiceContractAttributeWebGetAttribute , WebInvokeAttribute och .
[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 interfaceKommentar
Som standard WebInvokeAttribute mappar POST-anrop till åtgärden. Du kan dock ange HTTP-metoden (till exempel HEAD, PUT eller DELETE) för att mappa till åtgärden genom att ange parametern "method=". WebGetAttribute har inte parametern "method=" och mappar bara GET-anrop till tjänståtgärden.
Implementera tjänstkontraktet.
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
Värd för tjänsten
Skapa ett WebServiceHost objekt.
WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/"));Dim host As WebServiceHost = New WebServiceHost(GetType(Service), New Uri("http://localhost:8000/"))Lägg till en ServiceEndpoint med WebHttpBehavior.
ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");Dim ep As ServiceEndpoint = host.AddServiceEndpoint(GetType(IService), New WebHttpBinding(), "")Kommentar
Om du inte lägger till en slutpunkt WebServiceHost skapar du automatiskt en standardslutpunkt. WebServiceHost lägger också till WebHttpBehavior och inaktiverar HTTP-hjälpsidan och funktionen För webbtjänsters beskrivningsspråk (WSDL) GET så att metadataslutpunkten inte stör HTTP-standardslutpunkten.
Att lägga till en icke-SOAP-slutpunkt med en URL med "" orsakar oväntat beteende när ett försök görs att anropa en åtgärd på slutpunkten. Orsaken till detta är att lyssnings-URI för slutpunkten är samma som URI:n för hjälpsidan (sidan som visas när du bläddrar till basadressen för en WCF-tjänst).
Du kan utföra någon av följande åtgärder för att förhindra att detta händer:
- Ange alltid en icke-tom URI för en icke-SOAP-slutpunkt.
 - Inaktivera hjälpsidan. Detta kan göras med följande kod:
 
ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>(); sdb.HttpHelpPageEnabled = false;Dim sdb As ServiceDebugBehavior = host.Description.Behaviors.Find(Of ServiceDebugBehavior)() sdb.HttpHelpPageEnabled = FalseÖppna tjänstvärden och vänta tills användaren trycker på RETUR.
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()Det här exemplet visar hur du är värd för en webbtjänst med ett konsolprogram. Du kan också vara värd för en sådan tjänst i IIS. Det gör du genom att ange WebServiceHostFactory klassen i en .svc-fil som följande kod visar.
<%ServiceHost language=c# Debug="true" Service="Microsoft.Samples.Service" Factory=System.ServiceModel.Activation.WebServiceHostFactory%>
Anropa tjänståtgärder som mappats till GET i en webbläsare
- Öppna en webbläsare, ange URL:en och
http://localhost:8000/EchoWithGet?s=Hello, world!tryck sedan på Retur. URL:en innehåller basadressen för tjänsten (http://localhost:8000/), slutpunktens relativa adress (""), tjänståtgärden som ska anropas ("EchoWithGet") och ett frågetecken följt av en lista med namngivna parametrar avgränsade med ett et-tecken (&). 
Anropa tjänståtgärder i kod
Skapa en instans av ChannelFactory<TChannel> inom ett
usingblock.using (ChannelFactory<IService> cf = new ChannelFactory<IService>(new WebHttpBinding(), "http://localhost:8000"))Using cf As New ChannelFactory(Of IService)(New WebHttpBinding(), "http://localhost:8000")Lägg till WebHttpBehavior anropen ChannelFactory<TChannel> i slutpunkten.
cf.Endpoint.Behaviors.Add(new WebHttpBehavior());cf.Endpoint.Behaviors.Add(New WebHttpBehavior())Skapa kanalen och anropa tjänsten.
IService channel = cf.CreateChannel(); string s; Console.WriteLine("Calling EchoWithGet via HTTP GET: "); s = channel.EchoWithGet("Hello, world"); Console.WriteLine($" Output: {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: {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)WebServiceHostStäng .
host.Close();host.Close()
Exempel
Följande är den fullständiga kodlistan för det här exemplet.
// 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: {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: {s}");
                    Console.WriteLine("");
                }
                Console.WriteLine("Press <ENTER> to terminate");
                Console.ReadLine();
                host.Close();
            }
            catch (CommunicationException cex)
            {
                Console.WriteLine($"An exception occurred: {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
Kompilera koden
När du kompilerar Service.cs referens System.ServiceModel.dll och System.ServiceModel.Web.dll.