Nasıl yapılır: Temel Bir WCF Web HTTP Hizmeti Oluşturma
Windows Communication Foundation (WCF), Web uç noktasını kullanıma sunan bir hizmet oluşturmanıza olanak tanır. Web uç noktaları XML veya JSON ile veri gönderir; SOAP zarfı yoktur. Bu konuda, böyle bir uç noktanın nasıl kullanıma sunulur?
Not
Web uç noktasının güvenliğini sağlamanın tek yolu, aktarım güvenliğini kullanarak HTTPS aracılığıyla kullanıma sunmadır. İleti tabanlı güvenlik kullanılırken, güvenlik bilgileri genellikle SOAP üst bilgilerine yerleştirilir ve SOAP olmayan uç noktalara gönderilen iletiler SOAP zarfı içermediğinden, güvenlik bilgilerini yerleştirecek hiçbir yer yoktur ve aktarım güvenliğine güvenmeniz gerekir.
Web uç noktası oluşturmak için
ile ServiceContractAttributeWebInvokeAttribute işaretlenmiş bir arabirim ve WebGetAttribute öznitelikleri 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 POST WebInvokeAttribute çağrılarını işleme eşler. Bununla birlikte, "method=" parametresini belirterek işlemle eşlenecek HTTP yöntemini (örneğin, HEAD, PUT veya DELETE) belirtebilirsiniz. WebGetAttribute bir "method=" parametresine sahip değildir ve yalnızca GET çağrılarını hizmet işlemine eşler.
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
Bir WebServiceHost nesne oluşturun.
WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/"));
Dim host As WebServiceHost = New WebServiceHost(GetType(Service), New Uri("http://localhost:8000/"))
ile WebHttpBehaviorbir ServiceEndpoint ekleyin.
ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
Dim ep As ServiceEndpoint = host.AddServiceEndpoint(GetType(IService), New WebHttpBinding(), "")
Not
Uç nokta eklemezseniz, WebServiceHost otomatik olarak bir varsayılan uç nokta oluşturur. WebServiceHost ayrıca, meta veri uç noktasının varsayılan HTTP uç noktasıyla karışmaması için HTTP Yardım sayfasını ve Web Hizmetleri Açıklama Dili (WSDL) GET işlevini ekler WebHttpBehavior ve devre dışı bırakır.
"" URL'si ile SOAP olmayan bir uç nokta eklemek, uç noktada bir işlemi çağırma girişiminde bulunulduğunda beklenmeyen davranışa neden olur. Bunun nedeni, uç noktanın dinleme URI'sinin yardım sayfasının URI'sine (WCF hizmetinin temel adresine göz attığınızda görüntülenen sayfa) ile aynı olmasıdır.
Bunun olmasını önlemek için aşağıdaki eylemlerden birini yapabilirsiniz:
- SOAP olmayan uç nokta için her zaman boş olmayan bir URI belirtin.
- Yardım sayfasını kapatın. Bu işlem aşağıdaki kodla yapılabilir:
ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>(); sdb.HttpHelpPageEnabled = false;
Dim sdb As ServiceDebugBehavior = host.Description.Behaviors.Find(Of ServiceDebugBehavior)() sdb.HttpHelpPageEnabled = False
Hizmet ana bilgisayarını açın ve kullanıcı ENTER tuşuna basana kadar bekleyin.
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()
Bu örnek, konsol uygulamasıyla Web Stili hizmeti barındırmayı gösterir. Bu tür bir hizmeti IIS içinde de barındırabilirsiniz. Bunu yapmak için aşağıdaki kodun WebServiceHostFactory gösterdiği gibi sınıfını bir .svc dosyasında belirtin.
<%ServiceHost language=c# Debug="true" Service="Microsoft.Samples.Service" Factory=System.ServiceModel.Activation.WebServiceHostFactory%>
Tarayıcıda GET ile eşlenmiş hizmet işlemlerini çağırmak için
- Bir web tarayıcısı açın, "
http://localhost:8000/EchoWithGet?s=Hello, world!
" URL'sini girin ve Enter tuşuna basın. 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 hizmet işlemlerini çağırmak için
Bir blok içinde
using
örneği ChannelFactory<TChannel> oluşturun.using (ChannelFactory<IService> cf = new ChannelFactory<IService>(new WebHttpBinding(), "http://localhost:8000"))
Using cf As New ChannelFactory(Of IService)(New WebHttpBinding(), "http://localhost:8000")
Çağrıları uç noktaya ChannelFactory<TChannel> ekleyinWebHttpBehavior.
cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
cf.Endpoint.Behaviors.Add(New WebHttpBehavior())
Kanalı oluşturun ve hizmeti çağırın.
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)
öğesini WebServiceHostkapatın.
host.Close();
host.Close()
Örnek
Aşağıda, bu örneğin tam kod listesi verilmiştir.
// 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
Kod derleme
Service.cs başvuru System.ServiceModel.dll ve System.ServiceModel.Web.dll derlenirken.