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 会话就可以正确地获取了。

相关内容

热门资讯

透视黑科技!智星菠萝可以辅助吗... 透视黑科技!智星菠萝可以辅助吗,wepoker-h5下载(透视)原生存在有挂(教你攻略)1、智星菠萝...
透视软件!pokemmo辅助官... 透视软件!pokemmo辅助官网,pokerrrr2辅助,真是真的有挂(2025教程)pokemmo...
透视能赢!拱趴大菠萝辅助神器,... 透视能赢!拱趴大菠萝辅助神器,德普之星透视辅助插件(透视)固有真的是有挂(2025新版技巧)1、金币...
透视讲解!epoker免费透视... 透视讲解!epoker免费透视脚本,拱趴大菠萝挂怎么安装,一贯是真的有挂(黑科技教程)1、这是跨平台...
透视工具!德州透视是真的假的,... 透视工具!德州透视是真的假的,wepoker免费脚本咨询(透视)本然存在有挂(爆料教程);1、点击下...
透视存在!哈糖大菠萝挂法,拱趴... 透视存在!哈糖大菠萝挂法,拱趴大菠萝挂,果然存在有挂(技巧教程)1、哈糖大菠萝挂法ai辅助优化,哈糖...
透视讲解!wepoker私人局... 透视讲解!wepoker私人局俱乐部辅助,wepoker破解器有用吗(透视)原来真的有挂(可靠教程)...
透视数据!uupoker透视,... 透视数据!uupoker透视,拱趴大菠萝自动计算机器人,其实存在有挂(教你攻略);1、操作简单,无需...
辅助透视!wepoker正确养... 辅助透视!wepoker正确养号方法,wepoker永久免费脚本(透视)竟然是真的有挂(2025版教...
透视攻略!pokemmo辅助脚... 透视攻略!pokemmo辅助脚本,pokemmo内置修改器,本来是有挂(黑科技教程);1、超多福利:...