摘要:在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中讀取值出來。

02

03

04

05

06

07

08

09

10

11

12

13

14

如果,該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了哦!

02

03

04

ReadOnly Property GetCookieContainer()
05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

參考資訊
http://www.codeproject.com/Articles/35119/Using-Session-State-in-a-Web-Service.aspx
範例:
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^