Silverlight控件不能直接访问会话变量,因为Silverlight控件是客户端控件。但是我们可以调用WCF服务来管理Silverlight中的会话。
我们必须在wcf服务中设置会话变量,如下所示。
<ServiceContract(Namespace:="")> _
<AspNetCompatibilityRequirements
(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class PersonService
<OperationContract()> _
Public Sub DoWork()
' Add your operation implementation here
End Sub
' Add more operations here and mark them with <OperationContract()>
<OperationContract()> _
Public Sub SetSessionVariable(ByVal Sessionkey As String)
System.Web.HttpContext.Current.Session("Key") = Sessionkey
System.Web.HttpContext.Current.Session.Timeout = 20
End Sub
<OperationContract()> _
Public Function GetSessionVariable() As String
Return System.Web.HttpContext.Current.Session("Key")
End Function
End Class
通过将服务引用到Silverlight应用程序,我们可以在.xaml页中设置会话变量,如下所示。
Dim client As Service.PersonServiceClient = New Service.PersonServiceClient()
'Calls the SetSessionVariable() and store values in the session.
client.SetSessionVariableAsync("Soumya")
We will get the session variable in the .xaml page by calling GetSessionVariable() where we want to check the session
Dim client As Service.PersonServiceClient = New Service.PersonServiceClient()
AddHandler client.GetSessionVariableCompleted, AddressOf client_GetSessionVariableCompleted
client.GetSessionVariableAsync()
Private Sub client_GetSessionVariableCompleted(ByVal sender As Object, ByVal e As GetSessionVariableCompletedEventArgs)
Try
If Not String.IsNullOrEmpty(e.Result) Then
MessageBox.Show(e.Result)
Else
MessageBox.Show("Your session has been expired")
End If
Catch ex As FaultException
End Try
End Sub