![](/img/trans.png)
[英]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.