我正在try 开发一款带有剃刀页面的应用程序.出于这个原因,虽然我可以在我的主页上查看添加到购物车中的产品ID和数量,并将其放置在/Cart
页面上开发人员工具的Application/Cookies
选项卡中的Cookie中,但我不能使用C#代码访问它们.我给出了主页和/Cart
页的曲奇图片.
Note::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;
}
C#代码我正在try 访问cookie:
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>();
}
在这里,我得到一个空输出,该行的输出为cartCookie:
.
我想做的是转移到一个简单的Electron 商务网站的产品添加到购物车与cookie的产品,其中不需要用户登录.但是,在执行此操作时,我无法访问C#端的Cookie.