WCF常見問題(1) -- WebService/WCF Session Cookie

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   ar   color   os   使用   

原文: WCF常見問題(1) -- WebService/WCF Session Cookie

在.net 3.0推出WCF之前使用的WebService,有的應用有使用Session保持一些資訊,在不同的WebMethod中共用儲存資訊。比如:保持登陸使用者的資訊等。其原理是應用ASP.NET相容模式,利用HttpContext來保持請求的上下文。

為了顯示WebService/WCF不同應用下的Session/Cookie應用,這裡分別建立兩個Service應用:一個是WebService Application(.net 4.0下沒有此模板,只有在.net 3.5以下版本中有),一個是WCFService Application(IIS宿主的WCF應用)
整體solution圖:


1. WebService Application(*.asmx) + .net 2.0 Client Proxy
可以看到 Login 方法裡將登入的 userName 儲存在 Session 裡。在 GetUserName 方法返回 Session 中的資料。
[WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][System.ComponentModel.ToolboxItem(false)]public class Service1 : System.Web.Services.WebService{ [WebMethod(EnableSession=true)] public void Login(string user) { var session = HttpContext.Current.Session; session["user"] = user; HttpContext.Current.Response.Cookies.Add(new HttpCookie("user", user)); } [WebMethod(EnableSession = true)] public string GetUserName() { return HttpContext.Current.Session["user"] as string; }}
先來看看 .net 2.0 中的用戶端如何保持 Session 的。
ASP.NET 中的用戶端也就是瀏覽器端會通過Cookie來保持 Session。所以對於 WebService 的用戶端需要自己去維護一個 CookieContainer。(服務端需要沒一個WebMethod都需要設定EnableSession=true)
CookieContainer cookieContainer = new CookieContainer();
而每次調用都必須添加這個cookieContainer的執行個體。
PS: .net 3.5裡仍然可以使用.net 2.0產生用戶端:Add Service Reference -> Advance -> Add Web Reference

添加完WebService Reference後用戶端調用:
using (var svc = new MyWebSvc.Service1()){ svc.CookieContainer = cookieContainer; svc.Login(textBox1.Text);}
再一次調用:
using (var svc = new MyWebSvc.Service1()){ svc.CookieContainer = cookieContainer; label1.Text = svc.GetUserName();}
OK,現在的用戶端實現了cookie的保持,每次調用Service方法時,Service會攜帶之前的cookie資訊,則在服務端則能識別調用的Session而返回對應的資料。

2. WebService Application(*.asmx) + .net 3.5 Client Proxy
服務端代碼沒有變化,用戶端引用則修改為 Add Service Reference .net 3.5 產生用戶端代理。
這次產生的用戶端代理中已經找不到 svc 中的 CookieContainer 屬性,難道不能保持用戶端 cookie 了嗎?
檢查用戶端產生 app.config (.net 3.5裡的WebService原來使用的是basicHttpBinding)
<system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="Service1Soap" allowCookies="false" ......
原來 allowCookies 預設設為 false 了,我們把它改為:true 就OK了。
using (var svc = new MyWCFWebSvc.Service1SoapClient()){ svc.Login(textBox1.Text);}
再次調用:
using (var svc = new MyWCFWebSvc.Service1SoapClient()){ label1.Text = svc.GetUserName();}

3. WCF Service Application(*.svc) + .net 3.5 Client Proxy
WCF的ServiceContract
[ServiceContract]public interface IService1{ [OperationContract] string GetUserName(); [OperationContract] void Login(string user);}
Service的實現,類似上面的WebMethod
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]public class Service1 : IService1{ public void Login(string user) { var session = HttpContext.Current.Session; session["user"] = user; HttpContext.Current.Response.Cookies.Add(new HttpCookie("user", user)); } public string GetUserName() { return HttpContext.Current.Session["user"] as string; }} 
WCF Service Application的工程模板中,預設是沒有啟用ASP.NET相容模式的,這個時候直接調用 HttpContext 將返回 null。
所以需要設定 AspNetCompatibilityRequirements 特性:
1)[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
2)服務端設定檔也需要修改,在 <system.serviceModel> 節點中,添加如下配置:
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
用戶端產生的設定檔 app.config 也同樣需要設定

<system.serviceModel>
        <bindings>
              <wsHttpBinding>
                  <binding name="WSHttpBinding_IService1" allowCookies="true" ......

 

運行效果:

 

上面的代碼中,cookie只在應用程式的生存周期內有效,也就是說當程式關閉,cookie就失效了。服務端也就不能取得對應的session資訊了。如果一定要實作類別似瀏覽器瀏覽網頁,今天登陸明天再開還能有效呢?那就得自己來維持這個CookieContainer了,也就是說持久化這個對象。不過遺憾的是在.net3.0以上版本直接添加Service Reference的本地代理中,並沒有CookieContainer屬性。只能選擇使用.net2.0產生用戶端代理。持久化CookieContainer的代碼如下:
 CookieContainer cookieContainer = new CookieContainer();private void Form1_Load(object sender, EventArgs e){ var cookieFile = "MyCookie.dat"; if (File.Exists(cookieFile)) { using (var fs = File.OpenRead(cookieFile)) { var bf = new BinaryFormatter(); cookieContainer = bf.Deserialize(fs) as CookieContainer; } }}private void Form1_FormClosing(object sender, FormClosingEventArgs e){ var cookieFile = "MyCookie.dat"; using (var fs = File.OpenWrite(cookieFile)) { var bf = new BinaryFormatter(); bf.Serialize(fs, cookieContainer); }} 

 

WCF常見問題(1) -- WebService/WCF Session Cookie

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.