如何:使用 HTTPS 创建自定义可靠会话绑定

本主题演示如何对可靠会话使用安全套接字层 (SSL) 传输安全。 若要通过 HTTPS 使用可靠会话,必须创建使用可靠会话和 HTTPS 传输协议的自定义绑定。 可使用代码以强制方式或在配置文件中以声明方式启用可靠会话。 此过程使用客户端配置文件和服务配置文件来启用可靠会话和 <httpsTransport> 元素。

此过程的关键部分是 <endpoint> 配置元素包含一个 bindingConfiguration 属性,该属性引用名为 reliableSessionOverHttps 的自定义绑定配置。 然后,<binding> 配置元素可以引用此名称来指定,通过包括 <reliableSession> 和 <httpsTransport> 元素来使用可靠会话和 HTTPS 传输。

有关此示例的源副本,请参阅基于 HTTPS 的自定义绑定可靠会话

使用 CustomBinding 配置服务以将可靠会话与 HTTPS 一起使用

  1. 为该类型的服务定义服务协定。

    [ServiceContract]
    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);
    }
    
  2. 在服务类中实现该服务协定。 请注意,在服务的实现内部,未指定地址或绑定信息。 无需编写代码以从配置文件检索地址或绑定信息。

    public class CalculatorService : ICalculator
    {
        public double Add(double n1, double n2)
        {
            return n1 + n2;
        }
        public double Subtract(double n1, double n2)
        {
            return n1 - n2;
        }
        public double Multiply(double n1, double n2)
        {
            return n1 * n2;
        }
        public double Divide(double n1, double n2)
        {
            return n1 / n2;
        }
    }
    
  3. 创建 Web.config 文件,并使用名为 reliableSessionOverHttps 的自定义绑定(使用可靠会话和 HTTPS 传输)为 CalculatorService 配置一个终结点。

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <system.serviceModel>
    
        <services>
          <service name="Microsoft.ServiceModel.Samples.CalculatorService" 
                   behaviorConfiguration="CalculatorServiceBehavior">
            <!-- 
              Use base address provided by the host 
            -->
            <endpoint address=""
                      binding="customBinding"
                      bindingConfiguration="reliableSessionOverHttps" 
                      contract="Microsoft.ServiceModel.Samples.ICalculator" />
            <!-- 
              The mex endpoint is exposed as 
              http://localhost/servicemodelsamples/service.svc/mex
            -->
            <endpoint address="mex"
                      binding="mexHttpBinding"
                      contract="IMetadataExchange" />
          </service>
        </services>
    
        <bindings>
          <customBinding>
            <binding name="reliableSessionOverHttps">
              <reliableSession />
              <httpsTransport />
            </binding>
          </customBinding>
        </bindings>
    
      </system.serviceModel>
    </configuration>
    
  4. 创建包含以下代码行的 Service.svc 文件:

    <%@ServiceHost language=c# Service="CalculatorService" %>

  5. 将 Service.svc 文件放到 Internet 信息服务 (IIS) 虚拟目录中。

使用 CustomBinding 配置客户端以将可靠会话与 HTTPS 一起使用

  1. 从命令行中使用 ServiceModel 数据实用工具 (Svcutil.exe),根据服务元数据生成代码。

    Svcutil.exe <Metadata Exchange (MEX) address or HTTP GET address>
    
  2. 生成的客户端包含 ICalculator 接口,该接口定义了客户端实现必须满足的服务协定。

    // Generated interface defining the ICalculator contract	
    [System.ServiceModel.ServiceContractAttribute(
    Namespace="http://Microsoft.ServiceModel.Samples",
    ConfigurationName="Microsoft.ServiceModel.Samples.ICalculator")]
    public interface ICalculator
    {
        [System.ServiceModel.OperationContractAttribute(
        Action="http://Microsoft.ServiceModel.Samples/ICalculator/Add",
        ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/AddResponse")]
        double Add(double n1, double n2);
    
        [System.ServiceModel.OperationContractAttribute(
        Action="http://Microsoft.ServiceModel.Samples/ICalculator/Subtract",
        ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/SubtractResponse")]
        double Subtract(double n1, double n2);
    
        [System.ServiceModel.OperationContractAttribute(
        Action="http://Microsoft.ServiceModel.Samples/ICalculator/Multiply",
        ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/MultiplyResponse")]
        double Multiply(double n1, double n2);
    
        [System.ServiceModel.OperationContractAttribute(
        Action="http://Microsoft.ServiceModel.Samples/ICalculator/Divide",
        ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/DivideResponse")]
        double Divide(double n1, double n2);
    }
    
  3. 生成的客户端应用程序还包含 ClientCalculator 的实现。 请注意,在服务的实现内部,未指定地址和绑定信息。 无需编写代码以从配置文件检索地址和绑定信息。

    // Implementation of the CalculatorClient
    public partial class CalculatorClient :
        System.ServiceModel.ClientBase<Microsoft.ServiceModel.Samples.ICalculator>,
        Microsoft.ServiceModel.Samples.ICalculator
    {
        public CalculatorClient()
        {
        }
    
        public CalculatorClient(string endpointConfigurationName) :
            base(endpointConfigurationName)
        {
        }
    
        public CalculatorClient(string endpointConfigurationName, string remoteAddress) :
            base(endpointConfigurationName, remoteAddress)
        {
        }
    
        public CalculatorClient(string endpointConfigurationName,
            System.ServiceModel.EndpointAddress remoteAddress) :
            base(endpointConfigurationName, remoteAddress)
        {
        }
    
        public CalculatorClient(System.ServiceModel.Channels.Binding binding,
            System.ServiceModel.EndpointAddress remoteAddress) :
            base(binding, remoteAddress)
        {
        }
    
        public double Add(double n1, double n2)
        {
            return base.Channel.Add(n1, n2);
        }
    
        public double Subtract(double n1, double n2)
        {
            return base.Channel.Subtract(n1, n2);
        }
    
        public double Multiply(double n1, double n2)
        {
            return base.Channel.Multiply(n1, n2);
        }
    
        public double Divide(double n1, double n2)
        {
            return base.Channel.Divide(n1, n2);
        }
    }
    
  4. 配置名为 reliableSessionOverHttps 的自定义绑定,以使用 HTTPS 传输和可靠会话。

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <system.serviceModel>
    
        <client>
          <!-- 
            This endpoint has an https address
          -->
          <endpoint name=""
                    address="https://localhost/servicemodelsamples/service.svc" 
                    binding="customBinding" 
                    bindingConfiguration="reliableSessionOverHttps" 
                    contract="Microsoft.ServiceModel.Samples.ICalculator" />
        </client>
    
        <bindings>
          <customBinding>
            <binding name="reliableSessionOverHttps">
              <reliableSession />
              <httpsTransport />
            </binding>
          </customBinding>      
        </bindings>
    
      </system.serviceModel>
    </configuration>
    
  5. 在应用程序中创建 ClientCalculator 的实例,然后调用服务操作。

    //Client implementation code.
    class Client
    {
        static void Main()
        {
            // Create a client with given client endpoint configuration
            CalculatorClient client = new CalculatorClient();
    
            // Call the Add service operation.
            double value1 = 100.00D;
            double value2 = 15.99D;
            double result = client.Add(value1, value2);
            Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);
    
            // Call the Subtract service operation.
            value1 = 145.00D;
            value2 = 76.54D;
            result = client.Subtract(value1, value2);
            Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);
    
            // Call the Multiply service operation.
            value1 = 9.00D;
            value2 = 81.25D;
            result = client.Multiply(value1, value2);
            Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);
    
            // Call the Divide service operation.
            value1 = 22.00D;
            value2 = 7.00D;
            result = client.Divide(value1, value2);
            Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);
    
            //Closing the client gracefully closes the connection and cleans up resources
            client.Close();
    
            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client.");
            Console.ReadLine();
        }
    }
    
  6. 编译并运行客户端。

.NET Framework 安全性

因为此示例中使用的证书是用 Makecert.exe 创建的测试证书,所以当你尝试从浏览器中访问 HTTPS 地址(例如 https://localhost/servicemodelsamples/service.svc)时,将出现安全警报。

请参阅