好的,所以我在Cristian Darie的一本书中以电子商务中的Beginning ASP.NET开头的一本书中关注了这个示例。该示例构建了一个名为BalloonShop的在线商店。我沿着左右,直到第17章,由于这个错误crusing当我的站点不再推出:ASP Cookie“对象引用未设置为对象的实例”
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: Object reference not set to an instance of an object.] 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(Boolean includeStagesBeforeAsyncPoint, Boolean 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,如果它没有看到它创建一个cookie,但现在它不知何故全部停止。直到第16章为止,我的表现都不错,但现在我有点不舒服,因为我不知道如何解决这个问题。有任何想法吗?谢谢!!
我相信你的代码比你收到的空引用异常更多的问题。我重写了getShoppingCartId方法并将其放在下面 - 希望它有帮助! – 99823 2013-04-04 15:46:29