Angular发出调用请求后,ASP.NETCore会话为空
创始人
2024-10-24 17:01:21
0
  1. 确认在 Startup.cs 中是否已配置会话:
public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddSession();
    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...

    app.UseSession();
    app.UseMvc();
}
  1. 在 API 控制器中添加 Session
[Route("api/[controller]")]
public class TestController : Controller
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public TestController(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    [HttpGet("[action]")]
    public void SetSession(string key, string value)
    {
        _httpContextAccessor.HttpContext.Session.SetString(key, value);
    }

    [HttpGet("[action]")]
    public string GetSession(string key)
    {
        return _httpContextAccessor.HttpContext.Session.GetString(key);
    }
}
  1. 确认在 Angular 服务中配置了 withCredentials
@Injectable()
export class ApiService {
  private getUrl(path: string): string {
    return `${environment.apiUrl}/${path}`;
  }

  constructor(private http: HttpClient) {}

  public post(path: string, body: any): Observable {
    const headers = new HttpHeaders().set('Content-Type', 'application/json');
    return this.http.post(this.getUrl(path), body, { headers, withCredentials: true });
  }

  public get(path: string): Observable {
    return this.http.get(this.getUrl(path), { withCredentials: true });
  }
}
  1. 确认在初始化时配置了 Cookie 策略:
services.ConfigureApplicationCookie(options =>
{
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
    options.Cookie.SecurePolicy = CookieSecurePolicy.None;
    options.Cookie.SameSite = SameSiteMode.None;
    options.LoginPath = "/";
    options.LogoutPath = "/";
});

通过以上步骤,Angular 发出调用请求后,ASP.NET Core 会话就可以正确地获取了。

相关内容

热门资讯

总算清楚"欢乐达人猜... 总算清楚"欢乐达人猜猜乐友挂吗"开挂(下载)辅助下载真是有挂-玩家教程;无需打开直接搜索微信(136...
2分钟细说"蜀山四川... 2分钟细说"蜀山四川辅助器下载渠道有哪些"开挂(脚本)辅助脚本有挂教学-揭秘教程;无需打开直接搜索微...
免费测试版"敢拍小程... >>您好:敢拍小程序靠谱吗确实是有挂的,很多玩家在这款敢拍小程序靠谱吗游戏中打牌都会发现很多用户的牌...
今日头条"中至赣牌圈... 今日头条"中至赣牌圈挂件价格明细"开挂(插件)辅助插件有挂攻略-AI教程中至赣牌圈挂件价格明细ai黑...
一分钟了解"福建微乐... 一分钟了解"福建微乐小程序修改器"开挂(软件)辅助软件有挂猫腻-大神讲解福建微乐小程序修改器ai黑科...
技术分享"圣盛鄂州晃... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
透视挂"福建十三水辅... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
透视挂"四川麻将口诀... 透视挂"四川麻将口诀顺口溜"开挂(平台)辅助平台有挂细节-曝光教程>>您好:软件加薇13670430...
透视系统"微信小游戏... 透视系统"微信小游戏辅助器"开挂(软件)辅助软件了解有挂-扑克教程;无需打开直接搜索打开薇:1367...
今日焦点"白银胡乐亲... 白银胡乐亲友房开挂教程视频分享装挂详细步骤在当今的网络游戏中,白银胡乐亲友房作为一种经典的娱乐方式,...