Ahm*_*jad 2 c# cookies asp.net-core asp.net-core-2.0
我使用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();
}
Run Code Online (Sandbox Code Playgroud)
这是IndexB操作:
public IActionResult IndexB()
{
var cookie = Request.Cookies["mykey"];
return View();
}
Run Code Online (Sandbox Code Playgroud)
这是启动类:
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?}");
});
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这可能与ASP.NET Core 2.1附带的GDPR相关功能有关。我的理解是,它允许网站定义哪些cookie对浏览器来说是必不可少的,而不必要的cookie将不会发送。
我能想到的第一件事就是简单地删除非必要Cookie的同意检查。不要在生产中这样做,因为这可能违反法规!。更改:
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
Run Code Online (Sandbox Code Playgroud)
至
services.Configure<CookiePolicyOptions>(options =>
{
// No consent check needed here
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
Run Code Online (Sandbox Code Playgroud)
解决此问题的第二种可能方法是将cookie声明为必不可少的,因此,无论同意检查结果如何,您的cookie都将被发送到浏览器。为此,请更改:
Response.Cookies.Append(
"mykey",
"myvalue",
new CookieOptions()
{
Expires = DateTime.Now.AddMinutes(10)
});
Run Code Online (Sandbox Code Playgroud)
与
Response.Cookies.Append(
"mykey",
"myvalue",
new CookieOptions()
{
Expires = DateTime.Now.AddMinutes(10),
// Marking the cookie as essential
IsEssential = true
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3616 次 |
| 最近记录: |