C#网页代码出错,不知道错在哪里

来源:百度知道 编辑:UC知道 时间:2024/06/30 12:51:34
看看我的代码:
第一页:
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("test"); //创建一个HttpCookie对象
DateTime dtNow = DateTime.Now; //设定cookie的生命周期,在这里定义为一个小时
TimeSpan tsMinute = new TimeSpan(0, 1, 0, 0);
cookie.Expires = dtNow + tsMinute;
cookie["user"] = TextBox1.Text.Trim().ToUpper();
cookie["pass"] = TextBox2.Text.Trim().ToUpper();
Response.Cookies.Add(cookie); //加入此cookie
Response.Redirect("Default2.aspx");
}
然后看看第二页代码:
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["test"];
String strCookieValue = cookie.Value.ToString();
Label2.Text = Request.Cookies["user"].Value.ToString();
}

运行出现的错误:

Label2.Text = Request.Cookies["user"].Value.ToString();
这句改成 Label2.Text = Request.Cookies["test"]["user"].ToString();

HttpCookie cookie = Request.Cookies["test"];并没有获得值,就会导致这个错误!

肯定是中两个地方出错了啊
String strCookieValue = cookie.Value.ToString();
Label2.Text = Request.Cookies["user"].Value.ToString();
未将对象引用设置到对象的实例的意思是你用了一个为null的对象去调用一个方法,也就是说 cookie.Value和Request.Cookies["user"].Value肯定有一个是null
要避免这样的错误出现,就要在调用对象的方法前判断一下是否为null
你把上面那两句改成
String strCookieValue="";
if(cookie.Value!=null)
{
strCookieValue=cookie.Value.ToString();
}
if(Request.Cookies["user"]!=null)
{
Label2.Text=Request.Cookies["user"].ToString();
}
就行了
这些都是习惯问题,要养成良好的代码习惯,不然会很累的