Instrukcje: Wymiana komunikatów w ramach sesji niezawodnej

W tym temacie opisano kroki wymagane do włączenia niezawodnej sesji przy użyciu jednego z powiązań udostępnianych przez system, które obsługują taką sesję, ale nie domyślnie. Niezawodna sesja jest niezwykle włączona przy użyciu kodu lub deklaratywnego w pliku konfiguracji. Ta procedura używa plików konfiguracji klienta i usługi, aby umożliwić niezawodną sesję i określić, że komunikaty docierają do tej samej kolejności, w której zostały wysłane.

Kluczową częścią tej procedury jest to, że element konfiguracji punktu końcowego zawiera bindingConfiguration atrybut odwołujący się do konfiguracji powiązania o nazwie Binding1. Element <konfiguracji powiązania> odwołuje się do tej nazwy, aby umożliwić niezawodne sesje, ustawiając enabled atrybut <elementu reliableSession> na truewartość . Należy określić uporządkowane gwarancje dostarczania dla niezawodnej sesji, ustawiając ordered atrybut na true.

Aby uzyskać kopię źródłową tego przykładu, zobacz Sesja niezawodna usług WS.

Konfigurowanie usługi za pomocą usługi WSHttpBinding w celu korzystania z niezawodnej sesji

  1. Zdefiniuj kontrakt usługi dla typu usługi.

    [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. Zaimplementuj kontrakt usługi w klasie usługi. Należy pamiętać, że informacje o adresie lub powiązaniu nie są określone wewnątrz implementacji usługi. Nie musisz pisać kodu w celu pobrania informacji o adresie lub powiązaniu z pliku konfiguracji.

    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. Utwórz plik Web.config, aby skonfigurować punkt końcowy dla elementuCalculatorService, który używa WSHttpBinding elementu z włączoną niezawodną sesją i uporządkowanym dostarczaniem wymaganych komunikatów.

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <system.serviceModel>
    
        <services>
          <service name="Microsoft.ServiceModel.Samples.CalculatorService">
    
            <!--
                 This endpoint is exposed at the base address provided by
                 host: http://localhost/servicemodelsamples/service.svc
    
                 Specify wsHttpBinding binding and a binding configuration
                 to use
            -->
            <endpoint address=""
                      binding="wsHttpBinding"
                      bindingConfiguration="Binding1"
                      contract="Microsoft.ServiceModel.Samples.ICalculator" />
    
            <!--
              The mex endpoint is exposed at
              http://localhost/servicemodelsamples/service.svc/mex
            -->
            <endpoint address="mex"
                      binding="mexHttpBinding"
                      contract="IMetadataExchange" />
          </service>
        </services>
    
        <!--
             Configures WSHttpBinding for reliable sessions with ordered
             delivery.
        -->
        <bindings>
          <wsHttpBinding>
            <binding name="Binding1">
              <reliableSession enabled="true" ordered="true" />
            </binding>
          </wsHttpBinding>
        </bindings>
    
      </system.serviceModel>
    </configuration>
    
  4. Utwórz plik Service.svc zawierający wiersz:

    <%@ServiceHost language=c# Service="CalculatorService" %>
    
  5. Umieść plik Service.svc w katalogu wirtualnym usług Internet Information Services (IIS).

Konfigurowanie klienta za pomocą usługi WSHttpBinding w celu korzystania z niezawodnej sesji

  1. Użyj narzędzia ServiceModel Metadata Tool (Svcutil.exe) z wiersza polecenia, aby wygenerować kod z metadanych usługi:

    Svcutil.exe <service's Metadata Exchange (MEX) address or HTTP GET address>
    
  2. Wygenerowany klient zawiera ICalculator interfejs definiujący kontrakt usługi, który musi spełniać implementacja klienta.

    //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. Wygenerowana aplikacja kliencka zawiera również implementację .ClientCalculator Należy pamiętać, że informacje o adresie i powiązaniu nie są określone w żadnym miejscu w implementacji usługi. Nie musisz pisać kodu w celu pobrania informacji o adresie lub powiązaniu z pliku konfiguracji.

    // 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. Svcutil.exe generuje również konfigurację klienta, który używa WSHttpBinding klasy . Nadaj plikowi konfiguracji nazwę App.config podczas korzystania z programu Visual Studio.

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <system.serviceModel>
    
        <client>
          <!-- 
            Specify wsHttpBinding binding and a binding configuration 
            to use
          -->
          <endpoint 
              address="http://localhost/servicemodelsamples/service.svc" 
              binding="wsHttpBinding" 
              bindingConfiguration="Binding1" 
              contract="Microsoft.ServiceModel.Samples.ICalculator" />
        </client>
    
        <!-- 
          Configures WSHttpBinding for reliable sessions with ordered 
          delivery
        -->
        <bindings>
          <wsHttpBinding>
            <binding name="Binding1">
              <reliableSession enabled="true" ordered="true" />
            </binding>
          </wsHttpBinding>
        </bindings>
    
      </system.serviceModel>
    </configuration>
    
  5. Utwórz wystąpienie ClientCalculator obiektu w aplikacji i wywołaj operacje usługi.

    //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. Skompiluj i uruchom klienta.

Przykład

Kilka powiązań dostarczonych przez system domyślnie obsługuje niezawodne sesje. Są to:

Aby zapoznać się z przykładem tworzenia niestandardowego powiązania obsługującego niezawodne sesje, zobacz How to: Create a Custom Reliable Session Binding with HTTPS (Jak utworzyć niestandardowe powiązanie niezawodnej sesji przy użyciu protokołu HTTPS).

Zobacz też