为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 ASP.NET Core 2.0 存储和恢复 cookie?

如何使用 ASP.NET Core 2.0 存储和恢复 cookie?

C#
慕哥9229398 2021-12-05 16:33:51
我使用 ASP.NET Core 创建了一个示例 Web 应用程序来测试 cookie 的存储和检索。不幸的是,我无法存储 cookie。我将首先请求一个 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?}");        });    }}
查看完整描述

3 回答

?
慕的地6264312

TA贡献1817条经验 获得超6个赞

我认为这可能与 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

  });


查看完整回答
反对 回复 2021-12-05
?
慕斯王

TA贡献1864条经验 获得超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();

    }


查看完整回答
反对 回复 2021-12-05
?
皈依舞

TA贡献1851条经验 获得超3个赞

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


查看完整回答
反对 回复 2021-12-05
  • 3 回答
  • 0 关注
  • 186 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信