Home > front end >  ASP.NET core Session startup issues
ASP.NET core Session startup issues

Time:04-01

I must be missing something silly..

I am trying to use sessions in my web app and whenever I try to run the site, it gives me this:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.ISession' while attempting to activate 'EcommerceWebsite.Controllers.HomeController'.

enter image description here

This is my startup:

public void ConfigureServices(IServiceCollection services)
        {

            // MVC Shit
            services.AddControllers(options => options.EnableEndpointRouting = false);

            // DBContext shit
            services.AddDbContextPool<ventsus7_InventoryContext>(options => 
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddScoped<IIMS, IMSSQL>();

            services.AddDbContext<EcommerceWebsiteContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            // Identity shit
            services.AddIdentity<EcommerceWebsiteUser, IdentityRole>(config =>
            {
                config.SignIn.RequireConfirmedEmail = true;
            })
                .AddDefaultUI()
                .AddEntityFrameworkStores<EcommerceWebsiteContext>().AddDefaultTokenProviders();

            services.AddAuthentication();
            services.AddAuthorization();

            // Cache
            services.AddMemoryCache();

            services.ConfigureApplicationCookie(options =>
           {
               options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
               options.SlidingExpiration = true;
               options.LoginPath = "/Identity/Account/Login";

           });

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromDays(10);
                options.Cookie.IsEssential = true;
            });


            // Payments Stuff
            StripeConfiguration.ApiKey = Configuration.GetSection("Stripe")["SecretKey"];
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }


            //app.UseHttpsRedirection();
            app.UseStaticFiles();

            //app.UseRouting();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });

        }

This is my controller:

private readonly ILogger<HomeController> _logger;
        private ventsus7_InventoryContext context;
        private readonly UserManager<EcommerceWebsiteUser> userManager;
        private ISession memorySession;
        private JsonSerializerSettings settings = new JsonSerializerSettings()
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        };

        public HomeController(ILogger<HomeController> logger, ventsus7_InventoryContext dbContext, UserManager<EcommerceWebsiteUser> userManager, ISession memorySession)
        {
            _logger = logger;
            context = dbContext;
            this.userManager = userManager;
            this.memorySession = memorySession;
        }

CodePudding user response:

For the best practice of using AddSession and ISession, you can refer to the following code.

HomeController:

private readonly ILogger<HomeController> _logger;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ISession _memorySession;
public HomeController(ILogger<HomeController> logger, IHttpContextAccessor accessor)
{
    _logger = logger;
    _httpContextAccessor = accessor;
    _memorySession = _httpContextAccessor.HttpContext.Session;
}
public string Set(string key)
{
    _memorySession.SetString("key", key);
    return "success";
}
public string Get()
{
    return _memorySession.GetString("key");
}

Startup.cs

...
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromDays(10);
    options.Cookie.IsEssential = true;
});

Test Result

enter image description here

enter image description here

  • Related