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

关于使用COOKIES未将对象使用到实例的问题
ASPX文件上写了个简单的BUTTON
CS里的代码
C# code

protected void btn_Click(object sender, EventArgs e)
           {
                Response.Cookies["姓名"].Value = "ri";
                Response.Redirect("Manager.aspx");
            }



然后manager.aspx页面
C# code

public partial class Manager : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Request.Cookies["姓名"].Value);
        Response.End();
    }
}



然后点击button后转跳到manager.aspx,直接显示

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

源错误: 


行 10: protected void Page_Load(object sender, EventArgs e)
行 11: {
行 12: Response.Write(Request.Cookies["姓名"].Value);
行 13: Response.End();
行 14: }
 

另外,刚刚去复制这个错误时,刷新了一下MANAGER.ASPX,有显示ri(COOKIES),但是再一刷新又错误了...
被这个COOKIES搞死了...
昨晚给COOKIES过期时间Response.Cookies["姓名"].Expires = DateTime.MaxValue;仍然不行.
后来百度了一下,说要判断COOKIES是否为NULL(IF REQUEST.COOKIES["姓名"] != null)这样,也试过了,总之就是压根cookies["姓名"]怎么弄他就是没有值,太纠结了.

------解决方案--------------------
C# code

/* 添加cookie */
HttpCookie cookie = new HttpCookie(CookieName);
            cookie.Value = HttpUtility.UrlEncode(val);
            if(Day > 0)
                cookie.Expires = DateTime.Now.AddDays(Day);
            HttpContext.Current.Response.Cookies.Add(cookie);

/* 判断非空 */
(HttpContext.Current.Request.Cookies[cookieName] != null);

------解决方案--------------------
Response.Cookies(“姓名”).Expires
------解决方案--------------------
string Name = mrm.id.ToString();
System.Web.HttpCookie cookie1 = new System.Web.HttpCookie("admin");
cookie1.Expires.AddMinutes(30);
cookie1.Value = mrm.LoginId;
Response.AppendCookie(cookie1);
Response.Redirect("Default.aspx?AHSDS=" + Maticsoft.DBUtility.DESEncrypt.Encrypt(Name) + "");



if (Request.Cookies["admin"] == null)
{
Response.Write("<script>top.location.href='Login.aspx';</script>");
}
else
{
lblMA.Text = Request.Cookies["admin"].Value;
}


你这么用看看