How to get and set cookies in web api 2

13,056

Solution 1

aspnet/web-api/overview/advanced/http-cookies

To add cookies just use create a CookieHeaderValue instance that represents the cookie. Then call the AddCookies extension method, which is defined in the System.Net.Http. HttpResponseHeadersExtensions class.

public HttpResponseMessage Get()
{
    var resp = new HttpResponseMessage();

    var cookie = new CookieHeaderValue("session-id", "12345");
    cookie.Expires = DateTimeOffset.Now.AddDays(1);
    cookie.Domain = Request.RequestUri.Host;
    cookie.Path = "/";

    resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
    return resp;
}

And to retrive cookies You can use Request.Headers.GetCookies

var cookie = Request.Headers.GetCookies(CartSessionName).FirstOrDefault();

Solution 2

CookieHeaderValue is in System.Net.Http.Formatting (NuGet: System.Net.Http.Formatting.Extension), which has been deprecated. Not sure where else to find it. Also, the latest NuGet version is 5.2.3, but when I use it in a standard .Net Framework (4.6.1) Web API app, I get a runtime error: "Could not load file or assembly 'System.Net.Http.Formatting, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference."

Later - found that CookieHeaderValue is now in Microsoft.AspNet.WebApi.Client. I'm using version 5.2.4 although version 5.2.7 is latest as of 10/09/2020. Use namespace System.Net.Http.Headers.

Share:
13,056
AP123
Author by

AP123

Updated on July 13, 2022

Comments

  • AP123
    AP123 almost 2 years

    I am designing an e-commerce shopping cart in ASP.NET. When user clicks 'add to cart', I am checking if the cookie contains a cart ID. If not, I create a new cart, else I retrieve the cart from the database. The following is the cart service class

    using LaptopMart.Contracts;
    using LaptopMart.Models;
    using System;
    using System.Linq;
    using System.Web;
    
    namespace LaptopMart.Services
    {
    public class CartService : ICartService
    {
        public const string CartSessionName = "eCommerceCart";
    
        private readonly IUnitOfWork _unitOfWork;
    
        public CartService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }
    
    
    
        public Cart GetCart(HttpContextBase httpContextBase, bool createIfNull)
        {
            HttpCookie cookie = httpContextBase.Request.Cookies.Get(CartSessionName);
            Cart cart = null;
            if (cookie != null)
            {
                string strCartId = cookie.Value;
                int cartId = 0;
                if (!string.IsNullOrEmpty(strCartId))
                {
                    cartId = Convert.ToInt32(strCartId);
                    cart = _unitOfWork.CartRepository.Read(cartId);
                }
                else if (createIfNull)
                {
                    cart = CreateNewCart(httpContextBase);
                }
    
            } else if (createIfNull)
            {
                cart = CreateNewCart(httpContextBase);
            }
    
            return cart;
        }
    
        private Cart CreateNewCart(HttpContextBase httpContextBase)
        {
            Cart cart = new Cart();
            _unitOfWork.CartRepository.Create(cart);
            _unitOfWork.Complete();
    
            HttpCookie cookie = new HttpCookie(CartSessionName);
            cookie.Value = Convert.ToString(cart.Id);
            cookie.Expires = DateTime.Now.AddDays(1);
            httpContextBase.Response.Cookies.Add(cookie);
    
            return cart;
        }
    
        public void AddToCart(int productId, HttpContextBase httpContextBase)
        {
            Cart cart = GetCart(httpContextBase, true);
            var cartItem = cart.CartItems.FirstOrDefault(c => c.ProductId == productId);
            if (cartItem == null)
            {
                cartItem = new CartItem()
                {
                    ProductId = productId,
                    Quantity = 1
                };
    
                cart.CartItems.Add(cartItem); 
            }
            else
            {
                cartItem.Quantity += 1;
            }
    
            _unitOfWork.Complete();
        }
    
        public void RemoveFromCart(int productId, HttpContextBase httpContextBase)
        {
            Cart cart = GetCart(httpContextBase, false);
            if (cart != null)
            {
                var cartItem = cart.CartItems.FirstOrDefault(c => c.ProductId == productId);
                cart.CartItems.Remove(cartItem);
                _unitOfWork.Complete();
            }
    
        }
    
    }
    }
    

    When user clicks add to cart, this is what I am doing currently from my MVC controller

     public ActionResult AddToCart(string id)
     {
          _cartService.AddToCart(id, this.HttpContext);
    
          return RedirectToAction("Index");
     }
    

    However, what I want to do is, when the user clicks "add to cart", I want to send an ajax call to the Web Api 2 controller which does not have HttpContext property. Can someone help me with how I would achieve that.