I am using a client app to connect to a web service for authenticated user only. Here is simplest 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 on client app (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 keep the session cookies value in this one!
However, it don’t work 🙁 . The ws.WelcomeMsg() is always return an empty string.
Oops, I think I’ve just found the solution for this problem. The CookieContainer is created by server and must be kept at client app. On btnSetName_Click, I change
into
And it works well now! Thanks you all.