ServiceDescription 範例展示了服務如何在執行時擷取其服務描述資訊。 此範例是以 用戶入門為基礎,並定義額外的服務作業,以傳回服務的描述性資訊。 傳回的資訊會列出服務的基位址和端點。 服務會使用 OperationContext、 ServiceHost和 ServiceDescription 類別來提供這項資訊。
在此範例中,用戶端是控制台應用程式(.exe),而服務是由 Internet Information Services (IIS) 所裝載。
備註
此範例的安裝程式和建置指示位於本主題結尾。
此範例擁有一個名為 IServiceDescriptionCalculator 的計算機合約的修改版本。 合約會定義名為 GetServiceDescriptionInfo 的其他服務作業,此作業會將多行字串傳回至用戶端,以描述服務的基位址或地址和服務端點。
[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public interface IServiceDescriptionCalculator
{
[OperationContract]
int Add(int n1, int n2);
[OperationContract]
int Subtract(int n1, int n2);
[OperationContract]
int Multiply(int n1, int n2);
[OperationContract]
int Divide(int n1, int n2);
[OperationContract]
string GetServiceDescriptionInfo();
}
的實作程式代碼 GetServiceDescriptionInfo 會使用 ServiceDescription 來列出服務端點。 因為服務端點可以有相對位址,所以會先列出服務的基位址。 若要取得這項資訊,程式代碼會使用 Current取得其作業內容。
ServiceHost 及其 ServiceDescription 對象從操作環境中獲取。 若要列出服務的基底端點,程式代碼會逐一查看服務主機的 BaseAddresses 集合。 若要列出服務的服務端點,程式代碼會逐一查看服務描述的端點集合。
public string GetServiceDescriptionInfo()
{
string info = "";
OperationContext operationContext = OperationContext.Current;
ServiceHost host = (ServiceHost)operationContext.Host;
ServiceDescription desc = host.Description;
// Enumerate the base addresses in the service host.
info += "Base addresses:\n";
foreach (Uri uri in host.BaseAddresses)
{
info += " " + uri + "\n";
}
// Enumerate the service endpoints in the service description.
info += "Service endpoints:\n";
foreach (ServiceEndpoint endpoint in desc.Endpoints)
{
info += " Address: " + endpoint.Address + "\n";
info += " Binding: " + endpoint.Binding.Name + "\n";
info += " Contract: " + endpoint.Contract.Name + "\n";
}
return info;
}
當您執行範例時,您會看到計算機運算,接著看到 GetServiceDescriptionInfo 作業返回的服務資訊。 在客戶端視窗中按 ENTER 鍵以關閉用戶端。
Add(15,3) = 18
Subtract(145,76) = 69
Multiply(9,81) = 729
Divide(22,7) = 3
GetServiceDescriptionInfo
Base addresses:
http://<machine-name>/ServiceModelSamples/service.svc
https://<machine-name>/ServiceModelSamples/service.svc
Service endpoints:
Address: http://<machine-name>/ServiceModelSamples/service.svc
Binding: WSHttpBinding
Contract: IServiceDescriptionCalculator
Address: http://<machine-name>/ServiceModelSamples/service.svc/mex
Binding: MetadataExchangeHttpBinding
Contract: IMetadataExchange
Press <ENTER> to terminate client.