日期:2014-05-18  浏览次数:20532 次

弱弱的问个cookie的问题
目的:登录时有3个值需要记录进入cookie中,待后面调出使用。

记录时,我的代码是这样的
  //记录用户名
  HttpCookie hck = new HttpCookie("UserName");
  hck.Value = this.txtUserName.Text;
  Response.Cookies.Add(hck);
  //记录权限
  HttpCookie hck = new HttpCookie("Power");
  hck.Value = "系统管理员";
  Response.Cookies.Add(hck);
  //记录班次
  HttpCookie hck = new HttpCookie("BanC");
  hck.Value = this.txtBanC.Text;
  Response.Cookies.Add(hck);
使用时,代码如下
  this.labName.Text = Request.Cookies["UserName"].Value;
  this.labPower.Text = Request.Cookies["Power"].Value;
  this.labBanC.Text = Request.Cookies["BanC"].Value;

问题:为什么在VS2008调试时没有提示问题,可以正常显示。但使用IIS时则提示:


“/”应用程序中的服务器错误。
--------------------------------------------

未将对象引用设置到对象的实例。 
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 

异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。

源错误: 


行 18: protected void Page_Load(object sender, EventArgs e)
行 19: {
行 20: this.labName.Text = Request.Cookies["UserName"].Value;
行 21: this.labPower.Text = Request.Cookies["Power"].Value;
行 22: this.labBanc.Text = Request.Cookies["BanC"].Value;
 
对cookie的理解不深,究竟哪儿出错了,应该如何修改代码。望赐教。

------解决方案--------------------
HttpCookie hck = new HttpCookie("UserName");
你这里使用三个相同的变量没有报错吗?换下变量再试下看看
------解决方案--------------------
//-------------将用户和密码保存到cookie里
HttpCookie bcookie = new HttpCookie("UserInfo");
bcookie.Values.Add("User_Name",DBClass.EncryptCookie( tbUserName.Value.Replace(" ", "")));
bcookie.Values.Add("User_Pwd", MD5(TextBox_Pwd.Text));
bcookie.Values.Add("User_Power", DBClass.EncryptCookie("0"));
//--------------读取要保存的时间
bcookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(bcookie);

HttpCookie cookies = Request.Cookies["UserInfo"];
Label1.Text = DBClass.DecryptCookie(cookies.Values["User_Name"]);