会话状态在asp.net core 2.1 api项目中不起作用

时间:2019-04-27 12:17:21

标签: asp.net-core-2.1

我创建了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;
            }






        }

1 个答案:

答案 0 :(得分:0)

尚不清楚您是否已在“配置”中将调用添加到“ 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();
}