Search code examples
c#asp.net-corecookiesrazor-pages.net-7.0

Cannot access the data in cookies with C# & .NET 7.0


I'm trying to develop an app with Razor pages. For this reason, although I can view the product IDs and quantities that I added to the cart on my homepage and placed in cookies in the Application/Cookies tab of the developer tools on my /Cart page, I cannot access them with C# code. I give the image of the cookies for the homepage and /Cart page in the picture.

enter image description here

Note: app.UseCookiePolicy(); in Program.cs is available.

Script where I create cookies:

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# code I am trying to access the cookies:

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>();
}

Here Console.WriteLine($"cartCookie: {cartCookie}"); I get an empty output as cartCookie: for the line.

What I want to do is to transfer the products added to the cart with cookies for a simple e-commerce website where user login is not required. However, I cannot access cookies on the C# side while doing this.


Solution

  • We can get cookie from Headers, try :

    //var Cookie1 = Request.Headers.Cookie;//get the cookie
    var Cookie = Request.Headers.Cookie.ToString();
    var cartCookie = Cookie.Split('=').Last(); //get cartCookie value 
    

    result:

    enter image description here