ASP.NET WEB——项目中Cookie与Session的用法

 ASP.NET WEB——项目中Cookie与Session的用法


目录

 ASP.NET WEB——项目中Cookie与Session的用法

前言

环境

Cookie用法

Session用法


前言

ASP.NET WEB是一门非常简单的课程内容,我们大概用三章的内容来包含所有的知识点,三章分为

1、ASP.NET WEB项目创建与文件上传操作

2、ASP.NET WEB项目中Cookie与Session的用法

3、ASP.NET WEB项目中GridView与Repeater数据绑定控件的用法

分为三章,基本上将具体的用法讲解完毕,配套的【Repeater】的基础项目视频包含【数据库CRUD操作】让你快速上手,解决你考试的后顾之忧。

环境

系统环境:【win11】

开发工具:【Visual Studio 2017】

数据库:【SQLServer 2019】


Cookie用法

创建测试页面【Index】

前台代码

<asp:TextBox runat="server" ID="userName" placeholder="cookie值"></asp:TextBox>
<hr />
<asp:Button runat="server" OnClick="Unnamed_Click" Text="存储Cookie"/>
<hr />
获取Cookie:<asp:Label runat="server" ID="show"></asp:Label>

后台代码

protected void Unnamed_Click(object sender, EventArgs e)
{
    //创建Cookie
    HttpCookie cookie = new HttpCookie("userName");
    //设置值
    cookie.Value = this.userName.Text;
    //这个设置过期时间的
    cookie.Expires = DateTime.MaxValue;
    //添加到Cookie中
    Response.Cookies.Add(cookie);
    //直接获取
    this.show.Text = Response.Cookies["userName"].Value;
}

Session用法

创建测试页面【SessionDemo】

前台代码

<asp:TextBox runat="server" ID="userName" placeholder="Session值"></asp:TextBox>
<hr />
<asp:Button runat="server" OnClick="Unnamed_Click" Text="存储Session" />
<hr />
获取Session:<asp:Label runat="server" ID="show"></asp:Label>

后台代码

protected void Unnamed_Click(object sender, EventArgs e)
{
    //存储session
    Session["userName"] = this.userName.Text;
    //获取Session
    this.show.Text = Session["userName"].ToString();
}

测试效果:

无论是Cookie和Session都是比较好用的,但是平时我用的都不是很多,对我个人来说我一个写后端的不太喜欢用,一般存储热数据都是Redis来直接处理。如果是登陆的话我也会校验客户端传递回的token。

猜你喜欢

转载自blog.csdn.net/feng8403000/article/details/129291798