VB.NET Cookie操作编译报错:'Add'不是System.Web.HttpCookie的成员
问题分析与修复
代码意图
这段代码的目的是:
- 点击Button1时,向名为
userinfo的Cookie中添加一组键值对 - 点击Button2时,读取
userinfoCookie中对应键的值,显示到TextBox1中
编译错误原因
Request.Cookies("userinfo")返回的是单个HttpCookie对象,该对象没有Add方法。原代码错误地把单个Cookie当成了Cookie集合来操作。
修复后的代码
Button1_Click 修正版
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click ' 先检查userinfo Cookie是否存在,不存在则创建 Dim userCookie As HttpCookie = Request.Cookies("userinfo") If userCookie Is Nothing Then userCookie = New HttpCookie("userinfo") End If ' 向Cookie的Values集合添加键值对 userCookie.Values.Add("<key>", "<value>") ' 将更新后的Cookie写回响应,确保客户端保存 Response.Cookies.Add(userCookie) End Sub
Button2_Click 优化版(增加空值判断)
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click Dim userCookie As HttpCookie = Request.Cookies("userinfo") ' 先判断Cookie和对应键是否存在,避免空引用错误 If userCookie IsNot Nothing AndAlso userCookie.Values("<key>") IsNot Nothing Then TextBox1.Text = userCookie.Values("<key>") Else TextBox1.Text = "" ' 或者提示Cookie不存在 End If End Sub
关键说明
- 单个
HttpCookie的子键存储在Values集合中,要添加子键需操作Values.Add - 修改Cookie后必须将其添加到
Response.Cookies,否则客户端不会保存更新 - 读取Cookie时建议增加空值判断,避免运行时空引用异常
内容的提问来源于stack exchange,提问作者Jevon Kendon
相关产品推荐
相关产品推荐

