【问题标题】:How to get and set cookies in web api 2如何在 web api 2 中获取和设置 cookie
【发布时间】:2018-01-09 13:36:00
【问题描述】:

我正在用 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 控制器中所做的事情

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

      return RedirectToAction("Index");
 }

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      CookieHeaderValue 在 System.Net.Http.Formatting (NuGet: System.Net.Http.Formatting.Extension) 中,已被弃用。不知道在哪里可以找到它。此外,最新的 NuGet 版本是 5.2.3,但是当我在标准 .Net Framework (4.6.1) Web API 应用程序中使用它时,我收到运行时错误:“无法加载文件或程序集 'System.Net.Http .Formatting、Version=5.2.4.0、Culture=neutral、PublicKeyToken=31bf3856ad364e35' 或其依赖项之一。找到的程序集的清单定义与程序集引用不匹配。"

      后来 - 发现 CookieHeaderValue 现在在 Microsoft.AspNet.WebApi.Client 中。我使用的是 5.2.4 版,尽管 5.2.7 版是 2020 年 10 月 9 日的最新版本。使用命名空间 System.Net.Http.Headers。

      【讨论】:

        猜你喜欢
        • 2015-04-24
        • 2014-10-23
        • 2018-12-21
        • 2017-12-25
        • 1970-01-01
        • 2017-02-04
        • 2018-09-21
        • 2015-10-30
        • 2022-07-07
        相关资源
        最近更新 更多