代码之家  ›  专栏  ›  技术社区  ›  Ahmad Javadi Nezhad

如何使用ASP.NET Core 2.0存储和还原Cookie?

  •  1
  • Ahmad Javadi Nezhad  · 技术社区  · 6 年前

    我创建了一个带有ASP.NET核心的示例web应用程序来测试cookie的存储和检索。不幸的是,我不能储存饼干。

    我读过这些问题来解答我的问题:

    Cookies in ASP.NET Core rc2

    Create cookie with ASP.NET Core

    Cookies and ASP.NET Core

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

    这是索引操作:

    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?}");
            });
        }
    }
    
    2 回复  |  直到 6 年前
        1
  •  5
  •   Mickaël Derriey    6 年前

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

    我能想到的第一件事就是简单地删除非必要cookies的同意检查。 不要在生产中这样做,因为你可能违反规定! . 更改:

    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
      });
    
        2
  •  0
  •   Mario Levesque    6 年前

    我正在使用ASP.NET core 2.2。以下是我的ConfigureServices(IServiceCollection服务)中的内容,用于将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();
        }
    

    祝你好运