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

我使用 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?}");

        });

    }

}


慕哥9229398
浏览 187回答 3
3回答

慕的地6264312

我认为这可能与 ASP.NET Core 2.1 附带的 GDPR 相关功能有关。我的理解是,它允许网站定义哪些 cookie 对浏览器来说是必不可少的,而那些非必需的则不会被发送。我能想到的第一件事就是简单地删除对非必要 cookie 的同意检查。不要在生产中这样做,因为你可能会违反规定!. 改变:services.Configure<CookiePolicyOptions>(options =>{&nbsp; &nbsp; options.CheckConsentNeeded = context => true;&nbsp; &nbsp; options.MinimumSameSitePolicy = SameSiteMode.None;});到services.Configure<CookiePolicyOptions>(options =>{&nbsp; &nbsp; // No consent check needed here&nbsp; &nbsp; options.CheckConsentNeeded = context => false;&nbsp; &nbsp; options.MinimumSameSitePolicy = SameSiteMode.None;});解决此问题的第二种可能方法是将您的 cookie 声明为必不可少的,因此无论同意检查结果如何,您的 cookie 都将被发送到浏览器。为此,请更改:Response.Cookies.Append(&nbsp; "mykey",&nbsp; "myvalue",&nbsp; new CookieOptions()&nbsp; {&nbsp; &nbsp; &nbsp; Expires = DateTime.Now.AddMinutes(10)&nbsp; });和Response.Cookies.Append(&nbsp; "mykey",&nbsp; "myvalue",&nbsp; new CookieOptions()&nbsp; {&nbsp; &nbsp; &nbsp; Expires = DateTime.Now.AddMinutes(10),&nbsp; &nbsp; &nbsp; // Marking the cookie as essential&nbsp; &nbsp; &nbsp; IsEssential = true&nbsp; });

慕斯王

我正在使用 ASP.NET 核心 2.2。这是我在 ConfigureServices(IServiceCollection services) 中将 HttpContextAccessor 注入我的控制器的内容。&nbsp; &nbsp; public void ConfigureServices(IServiceCollection services)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; services.AddMvc();&nbsp; &nbsp; &nbsp; &nbsp; //... some code&nbsp; &nbsp; &nbsp; &nbsp; //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();&nbsp; &nbsp; &nbsp; &nbsp; services.AddHttpContextAccessor();&nbsp; &nbsp; }这是我的控制器中的内容:&nbsp; &nbsp; private readonly IHttpContextAccessor _httpContextAccessor;&nbsp; &nbsp; public MySomethingController(IHttpContextAccessor httpContextAccessor)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //... some code&nbsp; &nbsp; &nbsp; &nbsp; this._httpContextAccessor = httpContextAccessor;&nbsp; &nbsp; }下面是 Action 方法的代码:[HttpGet]&nbsp; &nbsp; public IActionResult SomethingToDo()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //... some code for my controller&nbsp; &nbsp; &nbsp; &nbsp; //Section for handling cookies&nbsp; &nbsp; &nbsp; &nbsp; //set the key value in Cookie&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; SetCookie("MyOwnKey", "Hello World from cookie", 15.0);&nbsp; &nbsp; &nbsp; &nbsp; //read cookie from IHttpContextAccessor&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["MyOwnKey"];&nbsp; &nbsp; &nbsp; &nbsp; //or&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; string cookieValueFromRequest = GetCookie("MyOwnKey");&nbsp; &nbsp; &nbsp; &nbsp; //Delete the cookie object&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //RemoveCookie("MyOwnKey");&nbsp; &nbsp; &nbsp; &nbsp; ViewData["CookieFromContext"] = cookieValueFromContext;&nbsp; &nbsp; &nbsp; &nbsp; ViewData["CookieFromRequest"] = cookieValueFromRequest;&nbsp; &nbsp; &nbsp; &nbsp; return View();&nbsp; &nbsp; }然后我有以下方法:&nbsp; &nbsp; public string GetCookie(string key)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return Request.Cookies[key];&nbsp; &nbsp; }&nbsp; &nbsp; public void SetCookie(string key, string value, double? expireTime)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; CookieOptions option = new CookieOptions();&nbsp; &nbsp; &nbsp; &nbsp; if (expireTime.HasValue)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; option.Expires = DateTime.Now.AddMinutes(expireTime.Value);&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; option.Expires = DateTime.Now.AddMilliseconds(1);&nbsp; &nbsp; &nbsp; &nbsp; Response.Cookies.Append(key, value, option);&nbsp; &nbsp; }&nbsp; &nbsp; public void RemoveCookie(string key)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Response.Cookies.Delete(key);&nbsp; &nbsp; }我能够在另一个控制器中看到 cookie 值并将其传递给视图。我在家庭控制器中有这个:...&nbsp; &nbsp; private readonly IHttpContextAccessor _httpContextAccessor;&nbsp; &nbsp; private readonly IHostingEnvironment _hostingEnvironment;&nbsp; &nbsp; public HomeController(IHostingEnvironment hostingEnvironment, IHttpContextAccessor httpContextAccessor)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; this._hostingEnvironment = hostingEnvironment;&nbsp; &nbsp; &nbsp; &nbsp; this._httpContextAccessor = httpContextAccessor;&nbsp; &nbsp; }&nbsp; &nbsp; public IActionResult Index()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //read cookie from IHttpContextAccessor&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["MyOwnKey"];&nbsp; &nbsp; &nbsp; &nbsp; ViewData["CookieFromContext"] = cookieValueFromContext;&nbsp; &nbsp; &nbsp; &nbsp; return View();&nbsp; &nbsp; }

皈依舞

一个控制器暴露 HttpContext.Response.Cookies... 不需要通过 ConfigureServices 方法使用依赖注入,也不需要向控制器添加额外的属性。只需调用 HttpContext.Response.Cookies.Append(...);
打开App,查看更多内容
随时随地看视频慕课网APP