WCF FAQs (1)--WEBSERVICE/WCF Session Cookie

Source: Internet
Author: User

Original: WCF FAQ (1)--WEBSERVICE/WCF Session Cookie

The webservice used before. NET 3.0 introduced WCF, some applications use the session to keep some information, and to share storage information in different WebMethod. For example: To keep the user's information, such as landing. The principle is the applicationASP. NET compatibility modeUseHttpContextTo keep the requested context.

To show the Session/cookie applications under different WEBSERVICE/WCF applications, create two service apps here: one is WebService application (. NET 4.0 without this template, only in. Net 3.5 in the following versions), one is Wcfservice application (WCF app for IIS host)
Overall solution diagram:


1. WebService Application (*.asmx) +. NET 2.0 Client Proxy
You can see the login in the login method to save the userName in the Session. The GetUserName method returns the data in Session.
<textarea cols="50" rows="15" name="code" class="c-sharp">[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; }}</textarea>
Let's take a look at how the client in. NET 2.0 keeps the Session.
The client in ASP., which is the browser side, keeps the Session through cookies. So the WebService client needs to maintain a cookiecontainer for itself. (Service side need not a WebMethod all need to set Enablesession=true)
<textarea cols="50" rows="2" name="code" class="c-sharp">Cookiecontainer Cookiecontainer = new Cookiecontainer ();</textarea>
Each invocation must add an instance of this cookiecontainer.
PS:. NET 3.5 can still be used to build clients in. NET 2.0: Add Service Reference, Advance, add Web Reference

Client calls after adding WebService reference:
<textarea cols="50" rows="5" name="code" class="c-sharp">using (var svc = new Mywebsvc.service1 ()) {svc. Cookiecontainer = Cookiecontainer; Svc. Login (TextBox1.Text);}</textarea>
Call again:
<textarea cols="50" rows="5" name="code" class="c-sharp">using (var svc = new Mywebsvc.service1 ()) {svc. Cookiecontainer = Cookiecontainer; Label1. Text = svc. GetUserName ();}</textarea>
OK, now the client implements the cookie, and each time the service method is invoked, the service carries the previous cookie information, then the server can identify the session and return the corresponding data.

2. WebService Application (*.asmx) +. NET 3.5 Client Proxy
The server code does not change, and the client reference is modified to generate the client agent for the ADD service Reference. NET 3.5.
The Cookiecontainer attribute in the SVC has not been found in this generated client agent, can't we keep the client cookie?
Check that the client generates app. Config (. NET 3.5 in WebService originally using BasicHttpBinding)
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name= "Service1Soap" allowcookies= "false" ...
OriginallyallowcookiesDefault set tofalse, we changed it to:trueIt's OK.
<textarea cols="50" rows="4" name="code" class="c-sharp">using (var svc = new Mywcfwebsvc.service1soapclient ()) {svc. Login (TextBox1.Text);}</textarea>
Call again:
<textarea cols="50" rows="4" name="code" class="c-sharp">using (var svc = new Mywcfwebsvc.service1soapclient ()) {Label1. Text = svc. GetUserName ();}</textarea>

3. WCF Service Application (*.SVC) +. NET 3.5 Client Proxy
ServiceContract of WCF
<textarea cols="50" rows="9" name="code" class="c-sharp">[Servicecontract]public interface iservice1{[OperationContract] string getusername (); [OperationContract] void Login (string user);</textarea>
Service implementation, similar to the above WebMethod
<textarea cols="50" rows="15" name="code" class="c-sharp">[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; }}</textarea>
In the project template for WCF Service application, the default is that ASP. NET compatibility mode is not enabled, and calling HttpContext directly will return NULL.
So you need to set the Aspnetcompatibilityrequirements feature:
1) [Aspnetcompatibilityrequirements (Requirementsmode = AspNetCompatibilityRequirementsMode.allowed)]
2) The server configuration file also needs to be modified, in the <system.serviceModel> node, add the following configuration:
<servicehostingenvironment aspnetcompatibilityenabled= "true"/>
the client-generated configuration file, app. Config, also needs to be set

<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name= "Wshttpbinding_iservice1" allowcookies= "true" ...

Operating effect:

In the above code, the cookie is only valid for the lifetime of the application, i.e. when the program is closed, the cookie is invalidated. The server will not be able to get the corresponding session information. If you must implement a browser-like browse the Web, today landing tomorrow can still be effective? Then you have to maintain the cookiecontainer, that is, to persist the object. Unfortunately, there is no Cookiecontainer attribute in the local agent that adds the service reference directly above the. net3.0 version. You can only choose to use. net2.0 to generate the client agent. The code for persisting Cookiecontainer is as follows:
Cookiecontainer Cookiecontainer = new Cookiecontainer ();p rivate void Form1_Load (object sender, EventArgs e) {var co Okiefile = "MyCookie.dat"; if (file.exists (cookiefile)) {using (var fs = File.openread (Cookiefile)) {var bf = new Binar Yformatter (); 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 FAQ (1)--WEBSERVICE/WCF Session Cookie

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.