【问题标题】:How to store and restore cookies with ASP.NET Core 2.0?如何使用 ASP.NET Core 2.0 存储和恢复 cookie?
【发布时间】:2018-08-20 13:56:41
【问题描述】:

我使用 ASP.NET Core 创建了一个示例 Web 应用程序来测试 cookie 的存储和检索。很遗憾,我无法存储 cookie。

我已针对我的问题阅读了这些问题:

Cookies in ASP.NET Core rc2

Create cookie with ASP.NET Core

Cookies and ASP.NET Core

但不幸的是我没有找到一个好的答案。

我将首先请求一个 IndexA 操作来存储 cookie。代码运行没有任何错误,但是当我请求 IndexB 操作时。没有找到指定的值

这是 IndexA 动作:

public IActionResult IndexA()
{
   Response.Cookies.Append("mykey", "myvalue",
    new CookieOptions()
    {
        Expires = DateTime.Now.AddMinutes(10)
    });
  return View();
}

这是 IndexB 操作:

public IActionResult IndexB()
{
   var cookie = Request.Cookies["mykey"];
   return View();
}

这是启动类:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

【问题讨论】:

  • 您可以通过按 F12 并单击应用程序选项卡来检查浏览器 cookie。你可以在那里看到cookies
  • 感谢您的建议,我通过 Chrome 开发者工具检查了 Cookie - 但不幸的是,没有保存任何内容。
  • 欢迎您 :) 但我不明白为什么您的代码没有创建 cookie,我编写了与您相同的代码并且它有效。
  • 可能是时区问题,能否将有效期改为1年
  • 你的代码真的有效吗?太搞笑了。。

标签: c# cookies asp.net-core asp.net-core-2.0


【解决方案1】:

我认为这可能与 ASP.NET Core 2.1 附带的 GDPR 相关功能有关。我的理解是,它允许网站定义哪些 cookie 对浏览器来说是必需的或非必需的,并且不会发送非必需的。

我能想到的第一件事就是简单地删除非必要 cookie 的同意检查。 请勿在生产中这样做,因为您可能会违反法规!。 变化:

services.Configure<CookiePolicyOptions>(options =>
{
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.Configure<CookiePolicyOptions>(options =>
{
    // No consent check needed here
    options.CheckConsentNeeded = context => false;
    options.MinimumSameSitePolicy = SameSiteMode.None;
});

解决此问题的第二种潜在方法是将您的 cookie 声明为必不可少,因此无论同意检查结果如何,您的 cookie 都会发送到浏览器。 为此,请更改:

Response.Cookies.Append(
  "mykey",
  "myvalue",
  new CookieOptions()
  {
      Expires = DateTime.Now.AddMinutes(10)
  });

Response.Cookies.Append(
  "mykey",
  "myvalue",
  new CookieOptions()
  {
      Expires = DateTime.Now.AddMinutes(10),
      // Marking the cookie as essential
      IsEssential = true
  });

【讨论】:

  • 我申请了两种方式,但都不适合我,你能告诉我如何存储cookie和启动类
【解决方案2】:

我正在使用 ASP.NET 核心 2.2。这是我在 ConfigureServices(IServiceCollection services) 中将 HttpContextAccessor 注入到我的控制器中的内容。

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        //... some code
        //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddHttpContextAccessor();
    }

这是我的控制器中的内容:

    private readonly IHttpContextAccessor _httpContextAccessor;

    public MySomethingController(IHttpContextAccessor httpContextAccessor)
    {
        //... some code
        this._httpContextAccessor = httpContextAccessor;
    }

下面是 Action 方法的代码:

[HttpGet]
    public IActionResult SomethingToDo()
    {
        //... some code for my controller

        //Section for handling cookies
        //set the key value in Cookie  
        SetCookie("MyOwnKey", "Hello World from cookie", 15.0);

        //read cookie from IHttpContextAccessor 
        string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["MyOwnKey"];
        //or 
        string cookieValueFromRequest = GetCookie("MyOwnKey");

        //Delete the cookie object  
        //RemoveCookie("MyOwnKey");

        ViewData["CookieFromContext"] = cookieValueFromContext;
        ViewData["CookieFromRequest"] = cookieValueFromRequest;

        return View();
    }

那我有以下方法:

    public string GetCookie(string key)
    {
        return Request.Cookies[key];
    }

    public void SetCookie(string key, string value, double? expireTime)
    {
        CookieOptions option = new CookieOptions();
        if (expireTime.HasValue)
            option.Expires = DateTime.Now.AddMinutes(expireTime.Value);
        else
            option.Expires = DateTime.Now.AddMilliseconds(1);
        Response.Cookies.Append(key, value, option);
    }

    public void RemoveCookie(string key)
    {
        Response.Cookies.Delete(key);
    }

我能够在另一个控制器中看到 cookie 值并将其传递给视图。 我在家庭控制器中有这个:

...
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly IHostingEnvironment _hostingEnvironment;


    public HomeController(IHostingEnvironment hostingEnvironment, IHttpContextAccessor httpContextAccessor)
    {
        this._hostingEnvironment = hostingEnvironment;
        this._httpContextAccessor = httpContextAccessor;
    }

    public IActionResult Index()
    {
        //read cookie from IHttpContextAccessor 
        string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["MyOwnKey"];
        ViewData["CookieFromContext"] = cookieValueFromContext;

        return View();
    }

祝你好运

【讨论】:

  • 您能告诉我们如何更新 cookie 的值吗?我应该先删除它然后重新设置它吗?
  • @Anastasios Moraitis 您可能需要删除和添加。我没有尝试过,但智能感知只向我显示了 Append、Delete、Equals、GetHashCode、GetType 和 ToString 的方法。请注意,cookie 具有价值,但也可能会过期。通过“更新”,您可能希望替换值或过期或两者兼而有之。
【解决方案3】:

控制器暴露 HttpContext.Response.Cookies... 不需要通过 ConfigureServices 方法使用依赖注入,也不需要向控制器添加额外的属性。只需调用 HttpContext.Response.Cookies.Append(...);

【讨论】:

    猜你喜欢
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 2011-03-16
    • 2018-12-17
    • 2018-06-21
    相关资源
    最近更新 更多