[英]ASP.Net C# reference to element on Site.master returns: Object reference not set to an instance of an object
[英]Object reference not set to an instance of an object asp.net , c#
嗨,我尝试将CartID分配给字符串时遇到此错误。 非常感谢您的帮助。 谢谢
private static string CartID
{
get
{
HttpContext cont = HttpContext.Current;
string id = cont.Request.Cookies["ShopCartID"].Value;
if (cont.Request.Cookies["ShopCartID"] != null)
{
return id;
}
else
{
id = Guid.NewGuid().ToString();
HttpCookie cookie = new HttpCookie("ShopCartID", id);
int days = 7;
DateTime currentDate = DateTime.Now;
TimeSpan timeSpan = new TimeSpan(days, 0, 0, 0);
DateTime expiration = currentDate.Add(timeSpan);
cookie.Expires = expiration;
cont.Response.Cookies.Add(cookie);
return id.ToString();
}
}
}
您的问题中(课程本身除外)没有CartID
,所以我假设您的意思是ShopCartID
。
如果不存在具有该名称的cookie,则cont.Request.Cookies["ShopCartID"]
可能返回null
。 您不能在null
引用上调用成员(在这种情况下为Value
)。 您必须首先检查cookie是否为null
:
HttpCookie cookie = cont.Request.Cookies["ShopCartID"];
string id = cookie != null ? cookie.Value : null;
编辑
这种模式非常普遍,以至于我的通用代码存储库已定义如下:
public static class ObjectExtensions
{
public static TResult IfNotNull<TValue, TResult>(this TValue value, Func<TValue, TResult> @delegate)
where TValue : class
{
if (@delegate == null)
{
throw new ArgumentNullException("delegate");
}
return value != null ? @delegate(value) : default(TResult);
}
}
像这样使用:
string id = cont.Request.Cookies["ShopCartID"].IfNotNull(arg => arg.Value);
在访问Cookie值之前,请尝试进行空检查。 当前,您的代码调用cont.Request.Cookies [“ ShopCartID”]。Value,如果cookie不存在,它将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.