服务说明

ServiceDescription 示例演示了服务如何在运行时检索其服务说明信息。 此示例基于 入门,并定义了一个附加的服务操作,用于返回有关服务的描述性信息。 返回的信息列出了服务的基址和终结点。 该服务使用OperationContextServiceHostServiceDescription类提供此信息。

在此示例中,客户端是一个控制台应用程序 (.exe),服务是由 Internet 信息服务 (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.

设置、生成和运行示例

  1. 确保已为 Windows Communication Foundation 示例 执行One-Time 安装过程。

  2. 若要生成解决方案的 C# 或 Visual Basic .NET 版本,请按照 生成 Windows Communication Foundation 示例中的说明进行操作。

  3. 若要在单台计算机或跨计算机配置中运行示例,请按照 运行 Windows Communication Foundation 示例中的说明进行操作。