【问题标题】:session state doesn't work in asp.net core 2.1 api project会话状态在 asp.net core 2.1 api 项目中不起作用
【发布时间】:2019-04-27 21:19:29
【问题描述】:

我创建了 asp.net core 2.1 API 项目,需要在会话中保存所有用户数据和权限。

但是当我调用另一个 API 会话值时返回 null

谁能帮我解决这个问题?

在startup.cs中

    public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => false;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });

                services.AddSession();
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
                var sqlConnectionString = Configuration.GetConnectionString("DefaultConnection");
                services.AddDbContext<QDeskDevContext>(options => options.UseSqlServer(sqlConnectionString));
                DependencyInjectionConfig.AddScope(services);
                JwtTokenConfig.AddAuthentication(services, Configuration);
                services.AddCors(options =>
                {
                    options.AddPolicy("CorsPolicy",
                        builder => builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
                });

                services.AddSignalR();
                services.AddAuthorization(options =>
                {
                    options.AddPolicy("sessionHandling", policy => policy.Requirements.Add(new sessionRequirement()));
                });

                services.AddSingleton<IAuthorizationHandler, sessionAuthorizationHandler>();


}


我添加了app.UseSession();

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseSession();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseCors("CorsPolicy");
           app.UseMiddleware(typeof(ExcMiddleware));

            app.UseSignalR(routes =>
            {
                routes.MapHub<QDeskHub>("/QDesk");
            });
            app.UseAuthentication();
            app.UseCookiePolicy();
            app.UseMvc();

        }

我的 api 操作


     [HttpPost]
            public ActionResult login([FromBody]LoginVM loginVM)
            {

                TryValidateModel(loginVM);
                if (ModelState.IsValid)
                {
                    string encPassword = common.creatHashPW(loginVM.Password);
                    TblCpUsers checkedUser = _UserService.login(loginVM.Email, encPassword);
                    if (checkedUser != null)
                    {
                            string token = _UserService.BuildToken(checkedUser, loginVM.encPassword, loginVM.isPersistent, loginVM.language);

    // here i set session value 
                            HttpContext.Session.SetString("token", token);
                            return Ok(new { token = token });
            }
           }}

这里我要获取会话值

[HttpGet]
        public object GetUserProfileData()

        {

            var token = HttpContext.Session.GetString("token") ?? string.Empty; // token return null 
            // this is my problem
            string userId = HttpContext.User.Claims.ToList().Single(d => d.Type == "id").Value;

            if (userId != null)
            {
                user user = _userService.get_user_data_by_encId(userId);
                if (user != null)
                {
                    return _stCbUserServices.GetUserById(user.userInfo.UserId);

                }
                else
                {
                    return ResultFilter.exception;
                }
            }
            else
            {
                return ResultFilter.userNotFound;
            }






        }

【问题讨论】:

    标签: asp.net-core-2.1


    【解决方案1】:

    不清楚是否在Configure中添加了对“UseSession()”的调用?

    例如:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }
    
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSession(); // ----> Have you added this ?
        app.UseHttpContextItemsMiddleware();
        app.UseMvc();
    }
    

    【讨论】:

    • 我添加了它我的问题是当我尝试获取会话值时它返回 null
    • 看起来您正在服务器端代码中设置会话值,然后期望 API(可能是 JS)调用能够访问会话。默认情况下,会话 cookie 是“HttpOnly”并且通常不能被 JS 代码访问。您可以尝试将 HttpOnly 选项设置为 false - 添加会话时,然后查看您的代码是否有效。此外,您应该使用浏览器工具来查看会话 cookie 是否实际上是在您的登录方法上设置的并在响应中传回。然后在调用 API 时,应该验证 cookie 是否传回服务器。
    • 说了这么多,出于你尝试使用Session cookie的目的,绝对不推荐。如果可能,您应该避免使用会话状态。 Session 变量有严格的限制。在这里阅读所有内容:docs.microsoft.com/en-us/aspnet/core/fundamentals/…
    • 我尝试将“HttpOnly”设置为 false,但它不起作用。
    • 我需要存储用户数据以避免连接数据库服务时间你能推荐一些东西给我来存储用户数据而不是会话
    猜你喜欢
    • 2021-11-07
    • 2019-02-04
    • 2018-12-20
    • 2014-02-01
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 2021-11-30
    • 2021-07-25
    相关资源
    最近更新 更多