在asp.net中使用cookie时出现Nullpointerexception错误
本文关键字:Nullpointerexception 错误 cookie asp net | 更新日期: 2023-09-27 18:01:33
我在if条件下得到nullpointerexception。如何解决此错误。我的代码和错误描述如下:
error: System类型的异常。NullReferenceException'在System.Web.dll中发生,但未在用户代码中处理
错误发生在这一行:if (Request.Cookies[name]。Value != null)
public void SetCookie(string name, string value, int expiration)
{
HttpCookie cookie;
cookie = new HttpCookie(name);
if (Request.Cookies[name].Value != null)
{
DeleteCookie(name);
}
else
{
cookie.Value = value;
cookie.Expires = DateTime.Now.AddDays(expiration);
Response.Cookies.Add(cookie);
}
}
将您的方法更改为:
public void SetCookie(string name, string value, int expiration)
{
if(Request.Browser.Cookies)
{
if (Request.Cookies[name] != null)
{
DeleteCookie(name);
}
HttpCookie cookie;
cookie = new HttpCookie(name);
cookie.Value = value;
cookie.Expires = DateTime.Now.AddDays(expiration);
Response.Cookies.Add(cookie);
}
}