2

好的,所以我在 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 章我都做得很好,但现在我有点搞砸了,因为我不知道如何解决它。有任何想法吗?谢谢!!

4

2 回答 2

3

由于第 29 行是这样的:

string cartId = context.Request.Cookies["BalloonShop_CartID"].Value;

根据错误,唯一可能的情况是:

  • HTTP 上下文不可用(因为您在用户控件中,这极不可能)。
  • HTTP 请求或 cookie 集合为空(不可能是您获取 HTTP 上下文的方式)
  • Cookies["BalloonShop_CartID"]返回null,当您访问时这会爆炸.Value(很可能)

这些是对象引用异常的唯一可能原因,并且很可能是最后一项,cookie 返回 null。在查看整个代码示例时,奇怪的是它会检查 cookie,然后执行 null 检查以查看 cookie 是否不为 null;它应该执行以下操作(删除第 29 行)。

HttpContext context = HttpContext.Current;
 // check if the cart ID exists as a cookie
if (context.Request.Cookies["BalloonShop_CartID"] != null)
{
     // return the id
      return context.Request.Cookies["BalloonShop_CartID"].Value;
}
else
// if the cart ID doesn't exist in the cookie as well, generate a new ID
{
     .
     .
于 2013-04-04T15:09:31.213 回答
0

你也可以做这样的事情......

string cartId = context.Request.Cookies["BalloonShop_CartID"] != null 
    ? context.Request.Cookies["BalloonShop_CartID"].Value
    : "";

另外,我刚刚注意到你的代码有点乱,我在这里重写了它,我无法真正测试它,但希望它能让你更接近你的答案:

private static string GetShoppingCartId() {

    HttpContext context = HttpContext.Current;
    string cartId = context.Request.Cookies["BalloonShop_CartID"] != null 
        ? context.Request.Cookies["BalloonShop_CartID"].Value 
        : "";

    if (cartId == "")
    {
            // generate a new GUID
            cartId = Guid.NewGuid().ToString();
            int cartPersistDays = TheGateConfiguration.CartPersistDays;
            // create the cookie object and set its value
            context.Response.Cookies.Add(new HttpCookie("BalloonShop_CartID", cartId) {
                Expires = DateTime.Now.AddDays(cartPersistDays)
            });
     }

     return cartId;
 }
于 2013-04-04T15:35:52.553 回答