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.
Session state is maintained only if the client preserves the session cookie. The state management you use in a web service won't work if the client fails to take these steps. For these reasons, web services and state management don't offer a natural fit.
A Session is one of the server-side state management techniques that stores the user specific data across the user request. By default a session is not enabled in a web service; we need to enable it using the following procedure. The default time out of the session is 20, the same as any web application.
The WebMethod attribute is added to each method we want to expose as a Web Service.
ASMX provides the ability to build web services that send messages using the Simple Object Access Protocol (SOAP). SOAP is a platform-independent and language-independent protocol for building and accessing web services.
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
MainForm.m_ccSessionInfo = new System.Net.CookieContainer(); //Create a CookieContainer
ws.CookieContainer = MainForm.m_ccSessionInfo; //Set CookieContainer of the web service
into
ws.CookieContainer = new System.Net.CookieContainer(); //Create a CookieContainer
MainForm.m_ccSessionInfo = ws.CookieContainer; //Keep CookieContainer for later using
And it works well now! Thanks you all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With