Я только частично добавил корзину на свой тестовый сайт электронной коммерции.
Он по-прежнему не может оформить заказ или даже обновить количество товаров (хотя и собирается начать), но я смогу открыть страницу, отвечающую за отображение корзины покупок. Вместо этого он блокирует весь мой сайт.
При компиляции сайта я получаю следующую ошибку:
Ошибка сервера в приложении «/ Website». Ссылка на объект не установлена на
экземпляр объекта. Описание: произошло необработанное исключение
во время выполнения текущего веб-запроса. Пожалуйста, просмотрите
трассировка стека для получения дополнительной информации об ошибке и где она
возник в коде.
Сведения об исключении: System.NullReferenceException: ссылка на объект отсутствует
установить экземпляр объекта.
Ошибка источника:
Исходный код, который сгенерировал это необработанное исключение, может быть только
отображается при компиляции в режиме отладки. Чтобы включить это, пожалуйста, следуйте одному
из приведенных ниже шагов, затем запросите URL:
Добавьте директиву Debug = true вверху файла, который сгенерировал ошибку. Пример:
или
2) Добавьте следующий раздел в файл конфигурации вашего
Применение:
Обратите внимание, что этот второй метод будет вызывать все файлы в данном
приложение для компиляции в режиме отладки. Первая техника будет
вызвать компиляцию только этого конкретного файла в режиме отладки.
Внимание! Запуск приложений в режиме отладки
накладные расходы памяти / производительности. Вы должны убедиться, что приложение
Отладка отключена перед развертыванием в производственный сценарий.
Трассировка стека:
[NullReferenceException: ссылка на объект не установлена на экземпляр
объект.] ShoppingCartAccess.get_shoppingCartId () + 81
ShoppingCartAccess.GetItems () + 57
UserControls_CartSummary.PopulateControls () + 30
UserControls_CartSummary.Page_PreRender (Отправитель объекта, EventArgs e) +5
System.Web.Util.CalliHelper.EventArgFunctionCaller (IntPtr fp, Object
o, Объект t, EventArgs e) + 14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback (Отправитель объекта,
EventArgs e) +35 System.Web.UI.Control.OnPreRender (EventArgs e)
+8991986 System.Web.UI.Control.PreRenderRecursiveInternal ()
System.Web.UI.Control.PreRenderRecursiveInternal () + 175
System.Web.UI.Control.PreRenderRecursiveInternal () + 175
System.Web.UI.Page.ProcessRequestMain (Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+ 2496
Информация о версии: Microsoft .NET Framework Версия: 4.0.30319;
ASP.NET версия: 4.0.30319.237
Судя по ошибке трассировки стека (и, если я правильно оцениваю ошибку трассировки стека) - ошибка возникает при ShoppingCartAccess.get_shoppingCartId () . Поэтому я включаю код для 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));
}
}
Где я ошибся?