好的,所以我在 Cristian Darie 的一本名为“电子商务中的 ASP.NET 入门”的书中遵循这个示例。该示例构建了一个名为 BalloonShop 的在线商店。当我的网站由于这个错误而不再启动时,我一直在努力直到第 17 章:
Object reference not set to an instance of an object
Line 27: HttpContext context = HttpContext.Current;
Line 28: // try to retrieve the cart ID from the user cookie
Line 29: string cartId = context.Request.Cookies["BalloonShop_CartID"].Value;
Line 30: // if the cart ID isn't in the cookie...
Line 31: {
说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。
我的堆栈跟踪如下:
[NullReferenceException:对象引用未设置为对象的实例。] ShoppingCartAccess.get_shoppingCartId() in f:\TheGate\App_Code\ShoppingCartAccess.cs:29 ShoppingCartAccess.GetItems() in f:\TheGate\App_Code\ShoppingCartAccess.cs: 188 UserControls_CartSummary.PopulateControls() in f:\TheGate\UserControls\CartSummary.ascx.cs:25 UserControls_CartSummary.Page_PreRender(Object sender, EventArgs e) in f:\TheGate\UserControls\CartSummary.ascx.cs:18 System.Web。 Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, >EventArgs e) +14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35 System.Web.UI.Control.OnPreRender(EventArgs e) +8998946 System.Web.UI.Control.PreRenderRecursiveInternal() +103 System.Web.UI.Control.PreRenderRecursiveInternal() +175 System.Web.UI.Control.PreRenderRecursiveInternal() +175 System.Web.UI.Control.PreRenderRecursiveInternal() +175 System.Web.UI.Page.ProcessRequestMain(布尔型 includeStagesBeforeAsyncPoint,布尔型 includeStagesAfterAsyncPoint)+2496
就我有限的知识而言,我的代码似乎没问题(如下,来自我的 ShoppingCartAccess.cs 类):
private static string shoppingCartId
{
get
{
// get the current HttpContext
HttpContext context = HttpContext.Current;
// try to retrieve the cart ID from the user cookie
string cartId = context.Request.Cookies["BalloonShop_CartID"].Value;
// if the cart ID isn't in the cookie...
{
// check if the cart ID exists as a cookie
if (context.Request.Cookies["BalloonShop_CartID"] != null)
{
// return the id
return cartId;
}
else
// if the cart ID doesn't exist in the cookie as well, generate a new ID
{
// generate a new GUID
cartId = Guid.NewGuid().ToString();
// create the cookie object and set its value
HttpCookie cookie = new HttpCookie("BalloonShop_CartID", cartId);
// set the cookie's expiration date
int howManyDays = TheGateConfiguration.CartPersistDays;
DateTime currentDate = DateTime.Now;
TimeSpan timeSpan = new TimeSpan(howManyDays, 0, 0, 0);
DateTime expirationDate = currentDate.Add(timeSpan);
cookie.Expires = expirationDate;
// set the cookie on the client's browser
context.Response.Cookies.Add(cookie);
// return the CartID
return cartId.ToString();
}
}
}
}
在我的编程学习的这个阶段,我很无助。据我所知,我的程序正在寻找一个 cookie,如果它没有看到它,它会创建一个,但不知何故,现在一切都出错了。直到第 16 章我都做得很好,但现在我有点搞砸了,因为我不知道如何解决它。有任何想法吗?谢谢!!