Como: criar um serviço que requer sessões
As sessões criam um estado compartilhado entre dois ou mais pontos de extremidade que permite recursos úteis, como retornos de chamada, segurança de vários saltos e associações entre clientes e instâncias de serviço. Para obter mais informações sobre sessões em aplicativos WCF (Windows Communication Foundation), consulte Using Sessions.
Para especificar que um contrato exige sua associação para dar suporte a sessões
Crie um contrato de serviço que contenha pelo menos uma operação. Para obter um exemplo de como criar um contrato de serviço, consulte Como definir um contrato de serviço.
Modifique o System.ServiceModel.ServiceContractAttribute que declara o contrato definindo a propriedade ServiceContractAttribute.SessionMode como:
SessionMode.Required se esse contrato precisar ser executado em uma sessão.
SessionMode.Allowed se esse contrato puder ser executado em uma sessão.
SessionMode.NotAllowed se esse contrato não deve ser executado em uma sessão.
Configure seu ponto de extremidade de serviço para usar uma associação que dê suporte a sessões. O exemplo de configuração a seguir mostra o uso do System.ServiceModel.WSDualHttpBinding, que dá suporte a uma sessão do WS
-
ReliableMessaging.<appSettings> <!-- use appSetting to configure base address provided by host --> <add key="baseAddress" value="http://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>
Exemplo
O código de exemplo a seguir mostra como especificar um requisito de sessão no nível do contrato e usar um arquivo de configuração para dar suporte a esse requisito com a associação System.ServiceModel.WSDualHttpBinding.
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);
}
}
}
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
<appSettings>
<!-- use appSetting to configure base address provided by host -->
<add key="baseAddress" value="http://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>