C# · 12月 24, 2021

c# – 在调用ASMX Web服务时维护会话

我正在使用客户端应用程序仅为经过身份验证的用户连接到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窗体,而不是Web基础):

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()总是返回一个空字符串.

解决方法 哎呀,我想我刚刚找到了这个问题的解决方案. CookieContainer由服务器创建,必须保存在客户端应用程序中.在btnSetName_Click上,我改变了 MainForm.m_ccSessionInfo = new System.Net.CookieContainer(); //Create a CookieContainerws.CookieContainer = MainForm.m_ccSessionInfo; //Set CookieContainer of the web service

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

它现在运作良好!谢谢大家.