asp.net - 如何在 web api 2 中获取和设置 cookie

标签 asp.net asp.net-web-api asp.net-web-api2 cart

我正在 ASP.NET 中设计电子商务购物车。当用户点击“添加到购物车”时,我正在检查 cookie 是否包含购物车 ID。如果没有,我创建一个新的购物车,否则我从数据库中检索购物车。 下面是购物车服务类

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

    }

}
}

当用户点击添加到购物车时,这就是我目前在我的 MVC Controller 中所做的

 public ActionResult AddToCart(string id)
 {
      _cartService.AddToCart(id, this.HttpContext);

      return RedirectToAction("Index");
 }

但是,我想要做的是,当用户单击“添加到购物车”时,我想向没有 HttpContext 属性的 Web Api 2 Controller 发送一个 ajax 调用。有人可以帮助我实现这一目标。

最佳答案

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

要添加 cookie,只需使用创建一个代表 cookie 的 CookieHeaderValue 实例。然后调用System.Net.Http 中定义的AddCookies 扩展方法。 HttpResponseHeadersExtensions 类。

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

要检索 cookie,您可以使用 Request.Headers.GetCookies

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

关于asp.net - 如何在 web api 2 中获取和设置 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48169402/

相关文章:

c# - asp.net mvc RedirectToAction ("Index") 与 Index()

asp.net - Angular URLSearchParams 不适用于多个参数

c# - 在 Web API 操作中返回时,某些属性不会被序列化

c# - 自托管 ASP.NET Web API 的 SSL 证书绑定(bind)在重启后丢失

asp.net - 配置 IIS 7 和 ASP.NET 应用程序进行 URL 路由

c# - ASP.Net Datagrid DataFormat String 未按要求格式化日期

c# - 无法将 Exam_Mapper 的类型转换为 IMapper 的类型

c# - WebAPI - 在 Controller 上未找到任何操作

asp.net-web-api - IdentityServer3和Web API在同一进程中

C# - 添加 UPS 跟踪 API 引用时出错