共用方式為


如何:使用 HTTPS 建立自定義可靠會話系結

本主題示範如何使用安全傳輸協定(SSL)來實現傳輸安全性並與可靠會話一起使用。 若要透過 HTTPS 使用可靠的工作階段,您必須建立使用可靠工作階段和 HTTPS 傳輸的自訂系結。 您可以使用程式碼或在組態檔中以宣告式啟用可靠的會話。 此程式會使用用戶端和服務組態檔來啟用可靠的會話和 <HTTPsTransport> 元素。

此程序的關鍵部分是 <端點> 組態元素包含參考 bindingConfiguration 名為 reliableSessionOverHttps之自定義系結組態的屬性。 系統中的<繫結>配置元素會參考這個名稱,藉此指定通過包含<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 檔案,以使用可靠會話和 HTTPS 傳輸的reliableSessionOverHttps自定義系結來設定 端點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 Information Services (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({value1},{value2}) = {result}");
    
            // Call the Subtract service operation.
            value1 = 145.00D;
            value2 = 76.54D;
            result = client.Subtract(value1, value2);
            Console.WriteLine($"Subtract({value1},{value2}) = {result}");
    
            // Call the Multiply service operation.
            value1 = 9.00D;
            value2 = 81.25D;
            result = client.Multiply(value1, value2);
            Console.WriteLine($"Multiply({value1},{value2}) = {result}");
    
            // Call the Divide service operation.
            value1 = 22.00D;
            value2 = 7.00D;
            result = client.Divide(value1, value2);
            Console.WriteLine($"Divide({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

另請參閱