Logging on ASMX Web Service Call

I use a client application to connect to a web service for an authenticated user only. Here is a simple example:
My web service code:

public class TestService : System.Web.Services.WebService { [WebMethod(EnableSession = true)] public string WelcomeMsg() { return "Hello: " + Session["UserName"] + "! Welcome to our store."; } [WebMethod(EnableSession = true)] public void SetUserName(string sName) { Session["UserName"] = sName; } } 

Here is my code in the client application (Windows form, not web base):

 private void btnSetName_Click(object sender, EventArgs e) { TestService.TestService ws = new TestService.TestService(); //Create a web service MainForm.m_ccSessionInfo = new System.Net.CookieContainer(); //Create a CookieContainer ws.CookieContainer = MainForm.m_ccSessionInfo; //Set CookieContainer of the web service ws.SetUserName(txtUserName.Text); //Set value of session ws = null; } private void btnWelcome_Click(object sender, EventArgs e) { TestService.TestService ws = new TestService.TestService(); //Create a web service ws.CookieContainer = MainForm.m_ccSessionInfo; //Set CookieContainer back string sWelcome = ws.WelcomeMsg(); //Get value from session property ws = null; System.Diagnostics.Debug.WriteLine(sWelcome); } 

In my example, MainForm.m_ccSessionInfo is a static member, I want to save the session cookie value in this!
However, this does not work :( Ws.WelcomeMsg () always returns an empty string.

+6
source share
2 answers

Unfortunately, I just found a solution to this problem. CookieContainer is created by the server and must be stored in the client application. On btnSetName_Click I am changing

 MainForm.m_ccSessionInfo = new System.Net.CookieContainer(); //Create a CookieContainer ws.CookieContainer = MainForm.m_ccSessionInfo; //Set CookieContainer of the web service 

in

 ws.CookieContainer = new System.Net.CookieContainer(); //Create a CookieContainer MainForm.m_ccSessionInfo = ws.CookieContainer; //Keep CookieContainer for later using 

And now it works well! Thank you everybody.

+8
source

try below

 private void btnWelcome_Click(object sender, EventArgs e) { TestService.TestService ws = new TestService.TestService(); //Create a web service ws.SetUserName(txtUserName.Text); string sWelcome = ws.WelcomeMsg(); System.Diagnostics.Debug.WriteLine(sWelcome); } 

When calling the btnSetName_Click and btnWelcome_Click methods, click webservice, consider your requirements as new sessions.

+1
source

Source: https://habr.com/ru/post/900476/


All Articles