我正在尝试使用 Razor 页面开发一个应用程序。因此,虽然我可以在主页上查看添加到购物车中并在
Application/Cookies
页面上开发人员工具的 /Cart
选项卡中放置在 Cookie 中的产品 ID 和数量,但我无法使用 C# 代码访问它们。我在图片中给出了主页和/Cart
页面的cookie图像。
注意:
app.UseCookiePolicy();
中的Program.cs
可用。
我创建 cookie 的脚本:
function addToCart(productId) {
var cart = getCart();
var existingProduct = cart.find(item => item.productId === productId);
if (existingProduct) {
existingProduct.count += 1;
} else {
cart.push({ productId: productId, count: 1 });
}
setCart(cart);
alert('Ürün sepete eklendi!');
}
function getCart() {
var cart = getCookie('cart');
if (!cart) {
cart = [];
} else {
try {
cart = JSON.parse(cart);
} catch (error) {
cart = [];
}
}
return cart;
}
function setCart(cart) {
setCookie('cart', JSON.stringify(cart), 7);
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length === 2) return parts.pop().split(";")[0];
}
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
var newCookie = name + "=" + (value || "") + expires + "; path=/";
console.log(newCookie);
document.cookie = newCookie;
}
我正在尝试访问 cookie 的 C# 代码:
public List<CartItem> CartItems { get; set; }
public void OnGet()
{
CartItems = GetCartItems();
}
private List<CartItem> GetCartItems()
{
var cartCookie = Request.Cookies["cart"];
Console.WriteLine($"cartCookie: {cartCookie}");
if (!string.IsNullOrEmpty(cartCookie))
{
try
{
return JsonConvert.DeserializeObject<List<CartItem>>(cartCookie);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing cart cookie: {ex.Message}");
}
}
return new List<CartItem>();
}
在这里
Console.WriteLine($"cartCookie: {cartCookie}");
我得到了一个空输出,作为该行的 cartCookie:
。
我想做的是将添加到购物车的产品用cookie转移到一个不需要用户登录的简单电子商务网站。但是,执行此操作时我无法访问 C# 端的 cookie。