HOW TO:裝載和執行基本 Windows Communication Foundation 服務
這是在建立基本 Windows Communication Foundation (WCF) 服務,及可以呼叫該服務的用戶端時,必須進行的六個工作中的第三個。 如需這六個工作的概觀,請參閱使用者入門教學課程主題。
本主題說明如何執行基本 Windows Communication Foundation (WCF) 服務。 這個程序包含下列步驟:
建立服務的基底位址。
建立服務的服務主機。
啟用中繼資料交換。
開啟服務主機。
這個程序之後的範例會列出這項工作所會撰寫的完整程式碼清單。 將下列程式碼加入 Program
類別中所定義的 Main()
方法。 這個類別是在您建立 Service
方案時所產生的。
若要設定服務的基底位址
針對服務的基底位址建立 Uri 執行個體。 這個 URI 會指定 HTTP 結構描述、您的本機電腦、連接埠號碼 8000 以及到服務的路徑 ServiceModelSample/Service,它是在服務合約中服務的命名空間所指定的。
Dim baseAddress As New Uri("https://localhost:8000/ServiceModelSamples/Service")
Uri baseAddress = new Uri("https://localhost:8000/ServiceModelSamples/Service");
若要裝載服務
匯入
System.ServiceModel.Description
命名空間。 這一行程式碼必須連同 using 或 imports 陳述式的其他部分,置於 Program.cs/Program.vb 檔案的頂端。Imports System.ServiceModel.Description
using System.ServiceModel.Description;
建立新的 ServiceHost 執行個體來裝載服務。 您必須指定可實作服務合約和基底位址的型別。 以這個範例來說,基底位址為
https://localhost:8000/ServiceModelSamples/Service
,而CalculatorService
是實作服務合約的型別。Dim selfHost As New ServiceHost(GetType(CalculatorService), baseAddress)
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);
新增擷取 CommunicationException 的 try-catch 陳述式,並將下列三個步驟中的程式碼新增至 try 區塊。 catch 子句應該顯示錯誤訊息然後呼叫
selfHost.Abort()
。Try ' ... Catch ce As CommunicationException Console.WriteLine("An exception occurred: {0}", ce.Message) selfHost.Abort() End Try
try { // ... } catch (CommunicationException ce) { Console.WriteLine("An exception occurred: {0}", ce.Message); selfHost.Abort(); }
新增可公開服務的端點。 若要執行這個步驟,您必須指定已公開端點的合約、繫結,以及端點的位址。 以這個範例來說,將
ICalculator
指定為合約、將WSHttpBinding
指定為繫結,並且將CalculatorService
指定為位址。 請注意,端點位置要為相對位址。 端點的完整位址為基底位址和端點位址的組合。 在這個情況中,完整位址為https://localhost:8000/ServiceModelSamples/Service/CalculatorService
。' Add a service endpoint selfHost.AddServiceEndpoint( _ GetType(ICalculator), _ New WSHttpBinding(), _ "CalculatorService")
selfHost.AddServiceEndpoint( typeof(ICalculator), new WSHttpBinding(), "CalculatorService");
注意: 從 .NET Framework 4 開始,如果沒有針對服務明確設定端點,則執行階段會在 ServiceHost 開啟時加入預設端點。 本範例會明確加入一個端點以示範這方面的做法。如需詳細資訊預設端點、繫結和行為的詳細資訊,請參閱簡化的組態及WCF 服務的簡化組態。 啟用中繼資料交換。 若要執行這個步驟,請新增服務中繼資料行為。 首先,建立 ServiceMetadataBehavior 執行個體,並將 HttpGetEnabled 屬性設定為 true,接著再將新行為加入至服務。如需詳細資訊 發行中繼資料時的安全性問題詳細資訊,請參閱Security Considerations with Metadata。
' Enable metadata exchange Dim smb As New ServiceMetadataBehavior() smb.HttpGetEnabled = True selfHost.Description.Behaviors.Add(smb)
ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; selfHost.Description.Behaviors.Add(smb);
開啟 ServiceHost 並等候傳入訊息。 當使用者按下 ENTER 鍵時,關閉 ServiceHost。
selfHost.Open() Console.WriteLine("The service is ready.") Console.WriteLine("Press <ENTER> to terminate service.") Console.WriteLine() Console.ReadLine() ' Close the ServiceHostBase to shutdown the service. selfHost.Close()
selfHost.Open(); Console.WriteLine("The service is ready."); Console.WriteLine("Press <ENTER> to terminate service."); Console.WriteLine(); Console.ReadLine(); // Close the ServiceHostBase to shutdown the service. selfHost.Close();
若要驗證服務是否執行中
從 Visual Studio 內執行 service.exe 工具。 在 Windows Vista 上執行時,服務必須以系統管理員權限的身分來執行。 因為 Visual Studio 是以系統管理員權限的身分執行,所以 service.exe 也要以系統管理員權限的身分執行。 您也可以利用系統管理員權限開啟命令提示字元執行,然後透過命令提示字元執行 service.exe。
開啟 Internet Explorer 並瀏覽到偵錯頁面 https://localhost:8000/ServiceModelSamples/Service。
範例
下列範例包含此教學課程上一個步驟的服務合約和實作,並且會將服務裝載到主控台應用程式中。 請將下列項目編譯到名為 Service.exe 的可執行檔中。
在編譯程式碼時,請務必參考 System.ServiceModel.dll。
Imports System
Imports System.ServiceModel
Imports System.ServiceModel.Description
Module Service
' Define a service contract.
<ServiceContract(Namespace:="http://Microsoft.ServiceModel.Samples")> _
Public Interface ICalculator
<OperationContract()> _
Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double
<OperationContract()> _
Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double
<OperationContract()> _
Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double
<OperationContract()> _
Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double
End Interface
' Service class that implements the service contract.
' Added code to write output to the console window.
Public Class CalculatorService
Implements ICalculator
Public Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Add
Dim result As Double = n1 + n2
Console.WriteLine("Received Add({0},{1})", n1, n2)
Console.WriteLine("Return: {0}", result)
Return result
End Function
Public Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Subtract
Dim result As Double = n1 - n2
Console.WriteLine("Received Subtract({0},{1})", n1, n2)
Console.WriteLine("Return: {0}", result)
Return result
End Function
Public Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Multiply
Dim result As Double = n1 * n2
Console.WriteLine("Received Multiply({0},{1})", n1, n2)
Console.WriteLine("Return: {0}", result)
Return result
End Function
Public Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Divide
Dim result As Double = n1 / n2
Console.WriteLine("Received Divide({0},{1})", n1, n2)
Console.WriteLine("Return: {0}", result)
Return result
End Function
End Class
Class Program
Shared Sub Main()
' Step 1 of the address configuration procedure: Create a URI to serve as the base address.
Dim baseAddress As New Uri("https://localhost:8000/ServiceModelSamples/Service")
' Step 2 of the hosting procedure: Create ServiceHost
Dim selfHost As New ServiceHost(GetType(CalculatorService), baseAddress)
Try
' Step 3 of the hosting procedure: Add a service endpoint.
' Add a service endpoint
selfHost.AddServiceEndpoint( _
GetType(ICalculator), _
New WSHttpBinding(), _
"CalculatorService")
' Step 4 of the hosting procedure: Enable metadata exchange.
' Enable metadata exchange
Dim smb As New ServiceMetadataBehavior()
smb.HttpGetEnabled = True
selfHost.Description.Behaviors.Add(smb)
' Step 5 of the hosting procedure: Start (and then stop) the service.
selfHost.Open()
Console.WriteLine("The service is ready.")
Console.WriteLine("Press <ENTER> to terminate service.")
Console.WriteLine()
Console.ReadLine()
' Close the ServiceHostBase to shutdown the service.
selfHost.Close()
Catch ce As CommunicationException
Console.WriteLine("An exception occurred: {0}", ce.Message)
selfHost.Abort()
End Try
End Sub
End Class
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace Microsoft.ServiceModel.Samples
{
// Define a service contract.
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
// Service class that implements the service contract.
// Added code to write output to the console window.
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
double result = n1 + n2;
Console.WriteLine("Received Add({0},{1})", n1, n2);
Console.WriteLine("Return: {0}", result);
return result;
}
public double Subtract(double n1, double n2)
{
double result = n1 - n2;
Console.WriteLine("Received Subtract({0},{1})", n1, n2);
Console.WriteLine("Return: {0}", result);
return result;
}
public double Multiply(double n1, double n2)
{
double result = n1 * n2;
Console.WriteLine("Received Multiply({0},{1})", n1, n2);
Console.WriteLine("Return: {0}", result);
return result;
}
public double Divide(double n1, double n2)
{
double result = n1 / n2;
Console.WriteLine("Received Divide({0},{1})", n1, n2);
Console.WriteLine("Return: {0}", result);
return result;
}
}
class Program
{
static void Main(string[] args)
{
// Step 1 of the address configuration procedure: Create a URI to serve as the base address.
Uri baseAddress = new Uri("https://localhost:8000/ServiceModelSamples/Service");
// Step 2 of the hosting procedure: Create ServiceHost
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);
try
{
// Step 3 of the hosting procedure: Add a service endpoint.
selfHost.AddServiceEndpoint(
typeof(ICalculator),
new WSHttpBinding(),
"CalculatorService");
// Step 4 of the hosting procedure: Enable metadata exchange.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
// Step 5 of the hosting procedure: Start (and then stop) the service.
selfHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
selfHost.Abort();
}
}
}
}
注意: |
---|
此類服務需要權限才能將 HTTP 位址註冊到電腦上,以便接聽。 系統管理員帳戶具有此權限,但是非系統管理員則必須被授與 HTTP 命名空間的權限。如需詳細資訊 如何設定命名空間保留區的詳細資訊,請參閱設定 HTTP 和 HTTPS。 在 Visual Studio 下執行時,必須以系統管理員權限的身分執行 service.exe。 |
服務目前正在執行中。 繼續進行 HOW TO:建立 Windows Communication Foundation 用戶端。 如需疑難排解的詳細資訊,請參閱使用者入門教學課程疑難排解。