【发布时间】:2020-05-14 08:31:58
【问题描述】:
我从我的 ASP.NET Web 表单应用程序创建了一个简单的 Web cookie。我正在尝试从单独的 .NET Core Web 应用程序中检索此 cookie。每当我尝试这样做时,.NET Core 应用程序都会不断返回 cookie 的空值。
这是在 ASP.NET Web 表单应用程序中创建 cookie 的方式:
protected void btn1_Click(object sender, EventArgs e)
{
HttpCookie Abc = new HttpCookie("Abc");
DateTime now = DateTime.Now;
//Abc Set the cookie value.
Abc.Value = txt1.Text;
// Set the cookie expiration date.
Abc.Expires = now.AddMinutes(1);
// Add the cookie.
Response.Cookies.Add(Abc);
}
这就是我尝试从 .NET Core 应用程序中读取此“Abc”cookie 的方式:
public void OnGet()
{
if (HttpContext.Request.Cookies["Abc"] != null)
{
Message = "ya";
}
else
{
Message = "no";
}
}
这是 ASP.NET CORE 应用的 Startup.cs 详细信息:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddDistributedMemoryCache();
// services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddHttpContextAccessor();
services.AddSession(options =>
{
options.Cookie.HttpOnly = true;
// Make the session cookie essential
options.Cookie.IsEssential = true;
});
services.Configure<CookiePolicyOptions>(options =>
{
// No consent check needed here
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
当我运行 ASP .NET Core 应用程序时,我能够按预期在浏览器中找到 cookie:
我花了好几个小时研究这个但没有成功。关于为什么我无法从 .Net Core 应用程序读取 cookie 的任何想法?我非常感谢任何反馈。
谢谢!
【问题讨论】:
-
您使用的是哪个版本的 .Net Core?
-
嗨@EdneyHolder,我正在使用netcoreapp3.0
标签: c# asp.net asp.net-core cookies session-cookies