我已经从我的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的任何想法?我非常感谢您的任何反馈。
谢谢!
[如果您的Web应用托管在同一域的子域中(例如app1.example.com和app2.example.com),则可以通过设置子域的HttpCookie对象到.example.com
HttpCookie Abc = new HttpCookie("Abc");
DateTime now = DateTime.Now;
Abc.Domain = ".example.com";
//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);