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

相关内容

热门资讯

三分钟教材!智星菠萝有挂吗(透... 三分钟教材!智星菠萝有挂吗(透视)本来是有辅助安装(哔哩哔哩)1、下载好智星菠萝有挂吗正确养号方法之...
四分钟策略!wepoker正确... 四分钟策略!wepoker正确养号方法(透视)确实是有辅助辅助(哔哩哔哩)1、每一步都需要思考,不同...
七分钟烘培!哈糖大菠萝怎么挂(... 七分钟烘培!哈糖大菠萝怎么挂(透视)真是真的有辅助安装(哔哩哔哩)1、游戏颠覆性的策略玩法,独创攻略...
第6分钟指引!aapoker脚... 第6分钟指引!aapoker脚本怎么用(透视)原来是有辅助教程(哔哩哔哩)1、aapoker脚本怎么...
6分钟手筋!德州辅助工具到底怎... 6分钟手筋!德州辅助工具到底怎么样(透视)竟然是有辅助安装(哔哩哔哩)1、德州辅助工具到底怎么样公共...
第二分钟方案!wepoker辅... 第二分钟方案!wepoker辅助透视软件(透视)果然存在有辅助插件(哔哩哔哩)wepoker辅助透视...
四分钟操作!wepoker有没... 四分钟操作!wepoker有没有挂(透视)原来真的有辅助开挂(哔哩哔哩)1、wepoker有没有挂免...
第五分钟指南!hhpkoer辅... 第五分钟指南!hhpkoer辅助器视频(透视)原来真的是有辅助插件(哔哩哔哩)1、hhpkoer辅助...
第2分钟办法!wepoker模... 第2分钟办法!wepoker模拟器哪个(透视)好像真的有辅助脚本(哔哩哔哩)1、下载好wepoker...
第3分钟绝活!sohoo po... 第3分钟绝活!sohoo poker辅助器(透视)一直是有辅助插件(哔哩哔哩)1、在sohoo po...