Angular创建的Cookie无法在ASP.NET Core 5中读取求助
在ASP.NET Core应用中尝试读取Angular应用创建的Cookie,但通过HttpContext.Request.Cookies始终无法找到该Cookie。客户端已确认Cookie设置成功,且Flutter应用添加域名后可正常访问该Cookie。
相关代码
C# 后端代码:
var cookie = Request.Cookies["test"]; // 始终返回null或空集合 services.AddCors(options => { options.AddDefaultPolicy(builder => builder.SetIsOriginAllowed(_ => true) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); });
Angular 前端代码:
setCookie() { this.cookieService.set('test', 'test', 36000000, '/', 'localhost'); }
针对跨域场景下Cookie无法读取的问题,可从以下几个方向排查修复:
确保Angular请求携带Credentials
Angular发起HTTP请求时,必须显式设置withCredentials: true,否则浏览器不会将Cookie发送到服务器:this.http.get('/api/your-endpoint', { withCredentials: true }).subscribe(...);调整Cookie的SameSite属性
跨域场景下,Cookie需要设置SameSite=None才能被跨域请求携带;若站点使用HTTPS(生产环境),还需开启Secure属性(localhost的HTTP环境可暂时忽略)。修改Angular的Cookie设置代码:setCookie() { this.cookieService.set('test', 'test', { expires: new Date(Date.now() + 36000000), path: '/', domain: 'localhost', sameSite: 'None', secure: window.location.protocol === 'https:' // 根据环境自动判断 }); }确认ASP.NET Core的CORS中间件顺序
必须在app.UseRouting()之后、app.UseAuthorization()之前添加app.UseCors(),否则CORS配置不会生效:app.UseRouting(); // CORS中间件需放在此处 app.UseCors(); app.UseAuthorization(); app.UseEndpoints(endpoints => { ... });检查Cookie域名匹配规则
若ASP.NET Core和Angular运行在不同端口(如Angular在4200,后端在5001),Cookie域名设置为localhost是正确的(Cookie不区分端口);如果是自定义域名,需确保域名一致或使用通配符(如.example.com)。
内容的提问来源于stack exchange,提问作者Siwar Hadj Ali

