您的位置:首页 > 移动开发

webform中四种状态机制 application,session,cookie,viewstate

2009-06-28 02:49 393 查看
application
我们可以在Global.asax的Application_Start函数中存储数据:

void Application_Start(object src, EventArgs e)
{
int exp = 0;
// population of dataset from ADO.NET query not shown
// Cache DataSet reference
Application["Experiment"] = exp;
}

现在你可以在任意页面下使用它:

private void Page_Load(object src, EventArgs e)
{
int expr = Int32.Parse((Application["Experiment"]));
}

基于程序级别的状态,所以信息是所有用户共享的

当站点重新启动时信息就会丢失,

对所有共享的信息(web中)进行写操作的时候都要注意对于锁的应用.

private void Page_Load(object sender, System.EventArgs e)
{
Application.Lock();
int expr = Int32.Parse((Application["Experiment"]));
if (expr>=something)
{
//do something
}
Else
{
//do something else
}
Application.UnLock();
//Some other thing goes here
}

Session

为用户会话状态保存信息的机制,

Session[“Value”] = abc;

值得注意的是,在默认状况下,当cookie不可用时,session也会失效,为了避免这种状况发生,可以在config文件中设置:

<configuration>
<system.web>
<sessionState cookieless="true" />
</system.web>
</configuration>

cookie

protected void Page_Load(Object sender, EventArgs E)
{
int expr = 0;
if (Request.Cookies["Expr"] == null)
{
// "Expr" cookie not set, set with this response
HttpCookie cokExpr = new HttpCookie("Expr");
cokExpr.Value = exprTextBox.Text;
Response.Cookies.Add(cokExpr);
expr = Convert.ToInt32(exprTextBox.Text);
}
else
{
// use existing cookie value
expr = Convert.ToInt32(Request.Cookies["Expr"].Value);
}
// use expr to customize page
}
viewstate 为用来保存本页控件状态而存在的一种信息,被保存在html的一个隐藏的<input>标签中,
由于这些状态信息每次通信都要来回传递,加重了网络压力,建议只在本地网络的应用中使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐