You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular调用ASP.NET Core 6 Web API时Set-Cookie头存在但Cookie未设置

问题解决:跨域请求后Cookie未存储的问题

针对你遇到的Angular前端调用ASP.NET Core API登录成功但Cookie未存储的问题,以下是具体的排查和解决步骤:

1. 确保Angular请求启用withCredentials标志

跨域请求携带Cookie的前提是前端请求必须开启withCredentials,浏览器才会处理响应中的Set-Cookie头。对于NSwag生成的客户端,你可以通过以下方式配置:

方式一:直接在客户端实例中设置

// 初始化NSwag生成的API客户端时添加withCredentials配置
const apiClient = new YourApiClientName('http://localhost:5001', undefined, {
  withCredentials: true
});

方式二:通过HTTP拦截器全局配置

创建拦截器统一为所有请求添加withCredentials:

// http-client.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable()
export class HttpClientInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler) {
    // 克隆请求并开启withCredentials
    const modifiedReq = request.clone({ withCredentials: true });
    return next.handle(modifiedReq);
  }
}

然后在app.module.ts中注册拦截器:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpClientInterceptor } from './http-client.interceptor';

@NgModule({
  providers: [
    { 
      provide: HTTP_INTERCEPTORS, 
      useClass: HttpClientInterceptor, 
      multi: true 
    }
  ]
})
export class AppModule { }

2. 调整Cookie的SameSite设置

当前配置中SameSiteMode.Strict会导致跨域场景下浏览器拒绝存储或携带Cookie,因为Strict模式仅允许同站请求使用Cookie。将其修改为SameSiteMode.Lax:

options.Cookie.SameSite = SameSiteMode.Lax;

Lax模式允许跨域场景下的安全请求(如GET)携带Cookie,同时也会正常存储登录响应中的Cookie,满足跨域认证需求。

3. 移除手动设置的Cookie Domain

不要手动指定options.Cookie.Domain = "localhost",不同浏览器对localhost的Domain处理存在兼容性问题。移除该配置后,浏览器会自动将Cookie绑定到后端API的域名(localhost:5001),后续跨域请求只要开启withCredentials,就会自动携带该Cookie。

4. 确认CORS策略的启用顺序

确保在Program.cs中UseCors的调用顺序正确,必须放在UseAuthentication和UseAuthorization之前:

app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseAuthorization();

5. 验证Cookie存储位置

登录请求完成后,打开浏览器开发者工具的Application标签,在Cookie列表中选择http://localhost:5001(而非Angular的localhost:4200),即可看到存储的认证Cookie。

内容的提问来源于stack exchange,提问作者daandsp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 01:22:36