ASP Cookie“对象引用未设置为对象的实例”

时间:2013-04-04 15:04:16

标签: asp.net

好的,所以我在Cristian Darie在电子商务中称为Beginning 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:对象引用未设置为对象的实例。]     F:\ TheGate \ App_Code \ ShoppingCartAccess.cs中的ShoppingCartAccess.get_shoppingCartId():29    F:\ TheGate \ App_Code \ ShoppingCartAccess.cs中的ShoppingCartAccess.GetItems():188    F:\ TheGate \ UserControls \ CartSummary.ascx.cs中的UserControls_CartSummary.PopulateControls():25    F:\ TheGate \ UserControls \ CartSummary.ascx.cs中的UserControls_CartSummary.Page_PreRender(Object sender,EventArgs e):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,如果它没有看到它创建一个,但不知何故它现在都绊倒了。我做得很好,直到第16章,但现在我有点搞砸,因为我不知道如何解决它。有任何想法吗?谢谢!

2 个答案:

答案 0 :(得分:3)

由于第29行是这样的:

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

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

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

这是对象引用异常的唯一可能原因,并且很可能是最后一项,cookie返回null。在查看整个代码示例时,检查cookie是奇怪的,然后进行空检查以查看cookie是否为空;它应该执行以下操作(删除第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
{
     .
     .

答案 1 :(得分: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;
 }