在Web Service上使用Session(Using Session State in a Web Service)

  • 11065
  • 0
  • 2009-09-25

摘要:在Web Service上使用Session(Using Session State in a Web Service)

雖然寫程式儘量不要用到Session,但是有時還是會用到它。在ASP.NET 2.0中Web AP中要讓Web Service保留Session的話,只要設定enableSession:=True就可以了! 以下建立2個Web Method,SetName是將值放到Session之中,而GetName則是從Session中讀取值出來。 

01 <WebMethod(enableSession:=True)> _
02     Public Sub SetName(ByVal vstrName As String)
03   Session("EmpName") = vstrName
04     End Sub

05
06
07     <WebMethod(enableSession:=True)> _
08     Public Function GetName() As String
09   If IsNothing(Session("EmpName")) Then
10       Return String.Empty
11   Else
12       Return Session("EmpName")
13   End If
14     End Function

如果,該Web Service在Web AP中的話,這樣就可以Work。但是,如果是純的Web Service的話(WSVC1),另外個Web AP(WebAP1)要去Call的話,直接SetName後,再取GetName的話,會回傳空字串,因為每次Call都視為新的Client。

那要如何讓WSVC1去保留Session呢? 一般來說,那就要用到了WebService的CookieContainer屬性哦!  以下的範例是建立1個CookieContainer把它放在Session之中,然後在Call WebService時,把它指定給CookieContainer屬性,這樣該WebService就會認得那個Session的票根,就取得到Session了哦!

01 Partial Class WebSvcSession
02     Inherits System.Web.UI.Page
03
04     Private

 

ReadOnly Property GetCookieContainer()
05   Get
06       If IsNothing(Session("CK")) Then
07     Session("CK") = New System.Net.CookieContainer
08       End If
09       Return Session("CK")
10   End Get
11
12     End Property
13
14     Protected Sub btnSetName2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSetName2.Click
15   Dim nbSvc As New NbSvc.Service
16   '設定Web Service的CookieContainer
17   nbSvc.CookieContainer = GetCookieContainer
18   nbSvc.SetName("RM_2:" & txtName.Text)
19   btnSetName2.Text = nbSvc.GetName
20
21     End Sub

22
23     Protected Sub btnGetName2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetName2.Click
24   Dim nbSvc As New NbSvc.Service
25   '設定Web Service的CookieContainer
26   nbSvc.CookieContainer = GetCookieContainer
27   btnGetName2.Text = nbSvc.GetName
28     End Sub

29
30
31 End Class

參考資訊

http://www.codeproject.com/Articles/35119/Using-Session-State-in-a-Web-Service.aspx

範例:

 WebAPPage.rar

WebService.rar

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^