services|webWEB SERVICES状态管理
在默认情况下,.NET下的WEB SERVICES是无状态的.不过可以用ASP.NET提供的状态管理
那就是SESSION和APPLICATION.这使得WEB SERVICES下状态管理变得简单了,只需使用WEBMETHOD属性的ENABLESESSION子属性就可[WEBMETHOD(ENABLESESSION=TRUE)]
服务端代码如下:
[WebMethod(EnableSession= true)]
public client GetClientState()
{
cstate = (client)Session["clientstate"];
if (cstate == null)
{
cstate = new client();
Session["clientstate"] = cstate;
}
return cstate;
}
[WebMethod(EnableSession = true)]
public void click()
{
client c = this.GetClientState();
c.requsest++;
}
}
public class client
{
public int requsest;
}
先创建一个CLIENT类,用于表示客户端连接的次数,GetClientState()方法用于返回当前用户的状态.
客户端代码如下:
partial class Form1 : Form
{
webstate.Service ws ;
webstate.client c;
public Form1()
{
InitializeComponent();
ws = new testwebstate.webstate.Service();
ws.CookieContainer = new System.Net.CookieContainer();
//设置COOKIE容器,以便代理对象能正确使用COOKIE来提供状态信息
}
private void button1_Click(object sender, EventArgs e)
{
ws.click();//每点击一次,当前用户的CLIENT STATE的REQUEST就++
c = ws.GetClientState();//获取状态信息
MessageBox.Show("you have click" + c.requsest + "times");
}
}
以上的是SEESION的状态管理,下面介绍APPLICATION.
服务端代码如下:
[WebServiceBinding(ConformanceClaims = WsiClaims.BP10, EmitConformanceClaims = true)]
public class Service : System.Web.Services.WebService
{
ArrayList clist;
[WebMethod]
public string GetHistory()
{
StringBuilder xbuider = new StringBuilder();//要添加USING SYSTEM.TEXT;
clist = (ArrayList)Application["client"];
if (clist == null)
{
clist = new ArrayList();
Application["client"] = clist;
}
foreach (client c in clist)
{
xbuider.Append(c.name + "" + c.request +"" + "\r\n");
}
return xbuider.ToString();
}
[WebMethod]
public void click(ref client c)//这里用的是传递对象的引用
{
clist = (ArrayList)Application["client"];
if (clist == null)
{
clist = new ArrayList();
Application["client"] = clist;
}
clist.Add(c);
}
}
public class client
{
public int request;
public string name;
}
客户端代码如下:
partial class Form1 : Form
{
webstate.client c;
public Form1()
{
InitializeComponent();
c = new testwebstate2.webstate.client();
c.name = "jisiki";
}
private void button1_Click(object sender, EventArgs e)
{
c.request++;
webstate.Service s = new testwebstate2.webstate.Service();
s.click(ref c);//这里用的是传递对象的引用
this.richTextBox1.Text = s.GetHistory();
}
}
对于WEB SERVICES而言,APPLICATION属性总是可用的,APPLICATION返回HTTPAPPLICATIONSTATE类
的一个实例,它能存储来自任何客户端的可访问的"名称/值"对.
WEB SERVICES状态管理
80酷酷网 80kuku.com