User 10734264 Ответов: 1

Сеанс не работает на .NET core 2.1


Я добавил Все это, но все еще не работает

вот это класс, запуске

public class Startup
   {
       public Startup(IHostingEnvironment env)
       {
           var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
               .AddEnvironmentVariables();
           Configuration = builder.Build();
       }

       public IConfiguration Configuration { get; }

       // This method gets called by the runtime. Use this method to add services to the container.
       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 => true;
               options.MinimumSameSitePolicy = SameSiteMode.None;
           });

           services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, opts => { opts.ResourcesPath = "Globalization"; })
               .AddDataAnnotationsLocalization()
               .AddSessionStateTempDataProvider();
           services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


           services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
           services.AddSession(options =>
           {
               options.Cookie.Name = ".Project.Session";
               // Set a short timeout for easy testing.
               options.IdleTimeout = TimeSpan.FromMinutes(30);
               options.Cookie.HttpOnly = true;
           });

           // Add application services.
           services.AddTransient<IEmailSender, AuthMessageSender>();
           services.AddTransient<ISmsSender, AuthMessageSender>();

           services.AddTransient<ICustomerTB1, CCustomerTB1>();

           services.AddTransient<IUsmUser, CUsmUser>();
           services.AddTransient<IUsmUserType, CUsmUserType>();
           services.AddTransient<IUsmOffice, CUsmOffice>();
           services.AddTransient<IUsmOfficeType, CUsmOfficeType>();

           services.AddTransient<ISycGender, CSycGender>();

           //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
       }

       // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
       public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
       {
           loggerFactory.AddConsole(Configuration.GetSection("Logging"));
           loggerFactory.AddDebug();

           if (env.IsDevelopment())
           {
               app.UseDeveloperExceptionPage();
               app.UseDatabaseErrorPage();
           }
           else
           {
               app.UseExceptionHandler("/Home/Error");
               app.UseHsts();
           }

           app.UseHttpsRedirection();
           app.UseStaticFiles();
           app.UseCookiePolicy();
           app.UseStatusCodePages();
           app.UseAuthentication();
           app.UseSession();

           var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
           app.UseRequestLocalization(options.Value);

           app.UseMvc(routes =>
           {
               routes.MapRoute(
                   name: "areaRoute",
                   template: "{area:exists}/{controller=Account}/{action=Login}/{id?}"
               );

               routes.MapRoute(
                   name: "default",
                   template: "{controller=Account}/{action=Index}/{id?}"
           );
           });
       }
   }


Что я уже пробовал:

and on controller i have done


HttpContext.Session.SetString("Name", "aadfafdaf");
var name = HttpContext.Session.GetString("Name");


если я выберу
var name = HttpContext.Session.GetString("Name");
на том же контроллере после добавления на сеанс он работает.

Но при другом действии контроллера он возвращает null.

1 Ответов

Рейтинг:
9

User 10734264

по умолчанию

services.Configure<CookiePolicyOptions>(options =>
            {              
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


менять
options.CheckConsentNeeded = context => false;

и это работает на меня.