Поделиться через


Как создать службу, для которой требуются сеансы

Сеансы создают общее состояние между двумя (и более) конечными точками, что обеспечивает полезные функции, такие как обратные вызовы, безопасность по всем участкам передачи и ассоциации между клиентами и экземплярами служб. Дополнительные сведения сеансах в приложениях Windows Communication Foundation (WCF) см. в разделе Использование сеансов.

Указание требования контракта о необходимости поддержки сеанса его привязкой

  1. Создайте контракт службы как минимум с одной операцией. Пример создания контракта службы см. в разделе Как определить контракт службы Windows Communication Foundation.

  2. Измените элемент System.ServiceModel.ServiceContractAttribute, объявляющий контракт, присвоив свойству System.ServiceModel.ServiceContractAttribute.SessionMode одно из следующих значений:

  3. Настройте конечную точку службы так, чтобы она использовала привязку, поддерживающую сеансы. В следующем примере конфигурации показано использование привязки System.ServiceModel.WSDualHttpBinding, поддерживающей сеанс WS-ReliableMessaging.

    <appSettings>
      <!-- use appSetting to configure base address provided by host -->
      <add key="baseAddress" value="https://localhost:8080/ServiceMetadata" />
    </appSettings>
    <system.serviceModel>
      <services>
        <service 
          name="Microsoft.WCF.Documentation.DuplexHello"
          behaviorConfiguration="mex"
        >
          <endpoint
            address="/DuplexService"
            binding="wsDualHttpBinding"
            contract="Microsoft.WCF.Documentation.IDuplexHello"
           />
          <endpoint
            address=""
            binding="mexHttpBinding"
            contract="IMetadataExchange"
          />
        </service>
      </services>
      <behaviors>
        <serviceBehaviors>
          <behavior name="mex" >
            <serviceMetadata httpGetEnabled="true" />
          </behavior>
        </serviceBehaviors>
      </behaviors>
    </system.serviceModel>
    

Пример

В следующем примере кода демонстрируется указание требования сеанса на уровне контракта и использование файла конфигурации для поддержки этого требования с помощью привязки System.ServiceModel.WSDualHttpBinding.


Imports System
Imports System.Collections.Generic
Imports System.ServiceModel
Imports System.Threading

Namespace Microsoft.WCF.Documentation
    <ServiceContract(Name:="SampleDuplexHello", Namespace:="http://microsoft.wcf.documentation", _
                     CallbackContract:=GetType(IHelloCallbackContract), SessionMode:=SessionMode.Required)> _
    Public Interface IDuplexHello
        <OperationContract(IsOneWay:=True)> _
        Sub Hello(ByVal greeting As String)
    End Interface

  Public Interface IHelloCallbackContract
    <OperationContract(IsOneWay := True)> _
    Sub Reply(ByVal responseToGreeting As String)
  End Interface

  <ServiceBehaviorAttribute(InstanceContextMode:=InstanceContextMode.PerSession)> _
  Public Class DuplexHello
      Implements IDuplexHello

    Public Sub New()
      Console.WriteLine("Service object created: " & Me.GetHashCode().ToString())
    End Sub

    Protected Overrides Sub Finalize()
      Console.WriteLine("Service object destroyed: " & Me.GetHashCode().ToString())
    End Sub

    Public Sub Hello(ByVal greeting As String) Implements IDuplexHello.Hello
      Console.WriteLine("Caller sent: " & greeting)
      Console.WriteLine("Session ID: " & OperationContext.Current.SessionId)
      Console.WriteLine("Waiting two seconds before returning call.")
      ' Put a slight delay to demonstrate asynchronous behavior on client.
      Thread.Sleep(2000)
      Dim callerProxy As IHelloCallbackContract = OperationContext.Current.GetCallbackChannel(Of IHelloCallbackContract)()
            Dim response = "Service object " & Me.GetHashCode().ToString() & " received: " & greeting
      Console.WriteLine("Sending back: " & response)
      callerProxy.Reply(response)
    End Sub
  End Class
End Namespace
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Threading;

namespace Microsoft.WCF.Documentation
{
  [ServiceContract(
    Name = "SampleDuplexHello",
    Namespace = "http://microsoft.wcf.documentation",
    CallbackContract = typeof(IHelloCallbackContract),
    SessionMode = SessionMode.Required
  )]
  public interface IDuplexHello
  {
    [OperationContract(IsOneWay = true)]
    void Hello(string greeting);
  }

  public interface IHelloCallbackContract
  {
    [OperationContract(IsOneWay = true)]
    void Reply(string responseToGreeting);
  }

  [ServiceBehaviorAttribute(InstanceContextMode=InstanceContextMode.PerSession)]
  public class DuplexHello : IDuplexHello
  {

    public DuplexHello()
    {
      Console.WriteLine("Service object created: " + this.GetHashCode().ToString());
    }

    ~DuplexHello()
    {
      Console.WriteLine("Service object destroyed: " + this.GetHashCode().ToString());
    }

    public void Hello(string greeting)
    {
      Console.WriteLine("Caller sent: " + greeting);
      Console.WriteLine("Session ID: " + OperationContext.Current.SessionId);
      Console.WriteLine("Waiting two seconds before returning call.");
      // Put a slight delay to demonstrate asynchronous behavior on client.
      Thread.Sleep(2000);
      IHelloCallbackContract callerProxy
        = OperationContext.Current.GetCallbackChannel<IHelloCallbackContract>();
      string response = "Service object " + this.GetHashCode().ToString() + " received: " + greeting;
      Console.WriteLine("Sending back: " + response);
      callerProxy.Reply(response);
    }
  }
}
<appSettings>
  <!-- use appSetting to configure base address provided by host -->
  <add key="baseAddress" value="https://localhost:8080/ServiceMetadata" />
</appSettings>
<system.serviceModel>
  <services>
    <service 
      name="Microsoft.WCF.Documentation.DuplexHello"
      behaviorConfiguration="mex"
    >
      <endpoint
        address="/DuplexService"
        binding="wsDualHttpBinding"
        contract="Microsoft.WCF.Documentation.IDuplexHello"
       />
      <endpoint
        address=""
        binding="mexHttpBinding"
        contract="IMetadataExchange"
      />
    </service>
  </services>
  <behaviors>
    <serviceBehaviors>
      <behavior name="mex" >
        <serviceMetadata httpGetEnabled="true" />
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>

См. также

Справочник

System.ServiceModel.ServiceContractAttribute
System.ServiceModel.ServiceContractAttribute.SessionMode
System.ServiceModel.SessionMode