【发布时间】:2018-08-20 13:56:41
【问题描述】:
我使用 ASP.NET Core 创建了一个示例 Web 应用程序来测试 cookie 的存储和检索。很遗憾,我无法存储 cookie。
我已针对我的问题阅读了这些问题:
Create cookie with 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