【问题标题】:How to read response cookies如何读取响应 cookie
【发布时间】:2021-04-22 07:39:51
【问题描述】:

ASP.NET 5 MVC 应用程序方法设置 HttpContext.Response cookie。 如何在同一请求中通过长调用链从控制器调用的其他方法中读取此 cookie 值?

响应采集接口中不存在该方法

public interface IResponseCookies
{
    void Append(string key, string value);
    void Append(string key, string value, CookieOptions options);
    void Delete(string key);
    void Delete(string key, CookieOptions options);
}

当前请求其他方法中设置的TempData值可以读取。为什么cookies不能?应该在 HttpContext.Items 中重复 cookie 设置还是有更好的方法?

背景:

购物车应用程序有从控制器调用的日志方法。

它必须记录cartid

如果用户第一次将产品添加到购物车,控制器会使用新的 guid 创建购物车 id 并将 carid cookie 添加到响应中。

logger 方法使用Request.Cookies["cartid"] 来记录购物车。

对于添加到购物车的第一个项目,它返回 null,因为 cookie 未设置为浏览器。

Response.Cookies["cartid"]

 不存在。

日志方法可以从很多地方调用。很难将cartid作为参数传递给它。

应用程序有从控制器调用的日志方法。它将控制器上下文记录到控制器使用的同一数据库中。

在使用 ASP.NET Core 应用程序模板创建的错误控制器中执行日志记录:

public async Task<IActionResult> Error()
{
    var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
    await logger.LogExceptionPage(exceptionHandlerPathFeature);
    HttpContext.Response.StatusCode = 500;
    return new ContentResult() {
        Content ="error"
    };
}

如何通过错误前执行的代码记录此方法中的响应cookie?

导致编译错误的代码:

public class CartController : ControllerBase
{
    const string cartid = "cartid";
    private readonly HttpContextAccessor ca;

    public CartController(HttpContextAccessor ca)
    {
        this.ca = ca;
    }

    public IActionResult AddToCartTest(int quantity, string product)
    {
        ca.HttpContext.Response.Cookies.Append(cartid, Guid.NewGuid().ToString());
        Log("AddToCartStarted");
        return View();
    }

    void Log(string activity)
    {
        Console.WriteLine($"{activity} in cart {ca.HttpContext.Response.Cookies[cartid]}");
    }
}

【问题讨论】:

标签: c# asp.net-core cookies asp.net-core-mvc asp.net-core-5.0


【解决方案1】:

您无法从 Response 读取 Cookie。您需要从请求中读取它,如下所示

ca.HttpContext.Request.Cookies[cartId];

cartId 是存储在 Cookie 中的值的键。

【讨论】:

  • 如果在同一个请求处理过程中创建了 cookie,则它在请求中不存在,Request.Cookies["cartid"] 返回 null 。回答中的代码不能用于读取刚刚创建但尚未发送到浏览器的 cookie。
猜你喜欢
  • 2016-03-02
  • 1970-01-01
  • 2013-09-02
  • 2021-04-22
  • 2012-09-30
  • 2016-09-06
  • 2015-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多