我正在使用客户端应用程序仅为经过身份验证的用户连接到Web服务。这是最简单的例子:
我的网络服务代码:
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;
}
}
以下是我在客户端应用上的代码(Windows窗体,而不是网络基础):
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);
}
在我的示例中,MainForm.m_ccSessionInfo是一个静态成员,我想在此会话中保留会话cookie值!
但是,它不起作用:(。ws.WelcomeMsg()总是返回一个空字符串。
答案 0 :(得分:8)
MainForm.m_ccSessionInfo = new System.Net.CookieContainer(); //Create a CookieContainer
ws.CookieContainer = MainForm.m_ccSessionInfo; //Set CookieContainer of the web service
到
ws.CookieContainer = new System.Net.CookieContainer(); //Create a CookieContainer
MainForm.m_ccSessionInfo = ws.CookieContainer; //Keep CookieContainer for later using
现在效果很好!谢谢大家。
答案 1 :(得分:1)
尝试以下
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);
}
调用btnSetName_Click方法和btn欢迎时单击webservice,将您的请求视为新会话。