asp.net cookie 中文乱码
编码使用的是UTF-8
登陆页面:
logon.aspx 页面:
<div class="username">
<label>用户名</label>
<asp:TextBox runat="server" ID="name"></asp:TextBox>
</div>
logon.aspx.cs
//创建名为username的cookie
HttpCookie cookie = new HttpCookie("username");
//cookie的过期时间
cookie.Expires = DateTime.Now.AddDays(1);
//cookie的值
cookie.Value =name.Text.Trim();
Response.Cookies.Add(cookie);
登陆成功,进入Default.aspx页面,代码如下:
//获取最新的前18条记录
private void GetAllCount()
{
//读取配置文件中的数据库连接字符串
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
con.Open();
//读取当前用户名
string name = Request.Cookies["username"].Value;
//按时间降序排列 任务状态为运行 接受的任务
SqlCommand cmd = new SqlCommand("SELECT top 18 Id,Title,Content FROM [Infor] where Status='运行' and ReceId=(select id from [User] where name='"+name+"') order by PublishTime desc", con);
SqlDataReader sdr = cmd.ExecuteReader();
source.DataSource = sdr;
source.DataBind();
sdr.Close();
con.Close();
}
------解决方案--------------------
用URL 编码
------解决方案--------------------
//cookie的值
cookie.Value =name.Text.Trim();改成cookie.Value =Server.HtmlEncode(name.Text.Trim().ToString());
string name = Request.Cookies["username"].Value;改成:string name = Request.Cookies["username"].Value.ToString();