While compiling ASP.NET ecommerce website receive: Object reference not set to an instance of an object

被刻印的时光 ゝ 提交于 2020-02-07 08:59:48

问题


I just partially added shopping cart to my ecommerce test-site.

It still can't do checkout, or even update quantity of items(about to start though) but I should be able to open the page responsible for displaying the shopping cart. Instead it bricks my entire website.

I get the following error when compiling the site:

Server Error in '/Website' Application. Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:

  1. Add a "Debug=true" directive at the top of the file that generated the error. Example:

or:

2) Add the following section to the configuration file of your application:

Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode.

Important: Running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario.

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.] ShoppingCartAccess.get_shoppingCartId() +81
ShoppingCartAccess.GetItems() +57
UserControls_CartSummary.PopulateControls() +30
UserControls_CartSummary.Page_PreRender(Object sender, EventArgs e) +5 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) +8991986 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

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.237

Judging from the stack trace error(and if I'm correct from judging the stack trace error) - the error appears to happen with ShoppingCartAccess.get_shoppingCartId(). Threfore I'm including the code for the ShoppingCartAccess.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Common;
using System.Data;

/// <summary>
/// Summary description for ShoppingCartAccess
/// </summary>
public class ShoppingCartAccess
{
    public ShoppingCartAccess()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    // returns the shopping cart ID for the current user
    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["Website_CartID"].Value;
            // if the cart ID isn't in the cookie...
            {
                // check if the cart ID exists as a cookie
                if (context.Request.Cookies["Website_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("Website_CartID", cartId);
                    // set the cookie's expiration date
                    int howManyDays = WebsiteConfiguration.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();
                }
            }
        }
    }

    // Add a new shopping cart item
    public static bool AddItem(string productId, string attributes)
    {
        // get a configured DbCommand object
        DbCommand comm = GenericDataAccess.CreateCommand();
        // set the stored procedure name
        comm.CommandText = "ShoppingCartAddItem";
        // create a new parameter
        DbParameter param = comm.CreateParameter();
        param.ParameterName = "@CartID";
        param.Value = shoppingCartId;
        param.DbType = DbType.String;
        param.Size = 36;
        comm.Parameters.Add(param);
        // create a new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@ProductID";
        param.Value = productId;
        param.DbType = DbType.Int32;
        comm.Parameters.Add(param);
        // create a new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@Attributes";
        param.Value = attributes;
        param.DbType = DbType.String;
        comm.Parameters.Add(param);
        // returns true in case of success and false in case of an error
        try
        {
            // execute the stored procedure and return true if it executes
            // successfully, and false otherwise
            return (GenericDataAccess.ExecuteNonQuery(comm) != -1);
        }
        catch
        {
            // prevent the exception from propagating, but return false to
            // signal the error
            return false;
        }
    }


    // Update the quantity of a shopping cart item
    public static bool UpdateItem(string productId, int quantity)
    {
        // get a configured DbCommand object
        DbCommand comm = GenericDataAccess.CreateCommand();
        // set the stored procedure name
        comm.CommandText = "ShoppingCartUpdateItem";
        // create a new parameter
        DbParameter param = comm.CreateParameter();
        param.ParameterName = "@CartID";
        param.Value = shoppingCartId;
        param.DbType = DbType.String;
        param.Size = 36;
        comm.Parameters.Add(param);
        // create a new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@ProductID";
        param.Value = productId;
        param.DbType = DbType.Int32;
        comm.Parameters.Add(param);
        // create a new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@Quantity";
        param.Value = quantity;
        param.DbType = DbType.Int32;
        comm.Parameters.Add(param);
        // returns true in case of success and false in case of an error
        try
        {
            // execute the stored procedure and return true if it executes
            // successfully, and false otherwise
            return (GenericDataAccess.ExecuteNonQuery(comm) != -1);
        }
        catch
        {
            // prevent the exception from propagating, but return false to
            // signal the error
            return false;
        }
    }

    // Remove a shopping cart item
    public static bool RemoveItem(string productId)
    {
        // get a configured DbCommand object
        DbCommand comm = GenericDataAccess.CreateCommand();
        // set the stored procedure name
        comm.CommandText = "ShoppingCartRemoveItem";
        // create a new parameter
        DbParameter param = comm.CreateParameter();
        param.ParameterName = "@CartID";
        param.Value = shoppingCartId;
        param.DbType = DbType.String;
        param.Size = 36;
        comm.Parameters.Add(param);
        // create a new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@ProductID";
        param.Value = productId;
        param.DbType = DbType.Int32;
        comm.Parameters.Add(param);
        // returns true in case of success and false in case of an error
        try
        {
            // execute the stored procedure and return true if it executes
            // successfully, and false otherwise
            return (GenericDataAccess.ExecuteNonQuery(comm) != -1);
        }
        catch
        {
            // prevent the exception from propagating, but return false to
            // signal the error
            return false;
        }
    }

    // Retrieve shopping cart items
    public static DataTable GetItems()
    {
        // get a configured DbCommand object
        DbCommand comm = GenericDataAccess.CreateCommand();
        // set the stored procedure name
        comm.CommandText = "ShoppingCartGetItems";
        // create a new parameter
        DbParameter param = comm.CreateParameter();
        param.ParameterName = "@CartID";
        param.Value = shoppingCartId;
        param.DbType = DbType.String;
        param.Size = 36;
        comm.Parameters.Add(param);
        // return the result table
        DataTable table = GenericDataAccess.ExecuteSelectCommand(comm);
        return table;
    }

    // Retrieve shopping cart items
    public static decimal GetTotalAmount()
    {
        // get a configured DbCommand object
        DbCommand comm = GenericDataAccess.CreateCommand();
        // set the stored procedure name
        comm.CommandText = "ShoppingCartGetTotalAmount";
        // create a new parameter
        DbParameter param = comm.CreateParameter();
        param.ParameterName = "@CartID";
        param.Value = shoppingCartId;
        param.DbType = DbType.String;
        param.Size = 36;
        comm.Parameters.Add(param);
        // return the result table
        return Decimal.Parse(GenericDataAccess.ExecuteScalar(comm));
    }

}

Where did I go wrong?


回答1:


It must be because the value of context.Request.Cookies["Website_CartID"] is null.

Write this line:

if(context.Request.Cookies["Website_CartID"]==null) return "0";

before this line:

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



回答2:


The context.Request.Cookies["Website_CartID"].Value looks suspicious. What if the cookie doesn't exist?



来源:https://stackoverflow.com/questions/8270509/while-compiling-asp-net-ecommerce-website-receive-object-reference-not-set-to-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!