A
A
Aricce2021-01-26 15:35:18
ASP.NET
Aricce, 2021-01-26 15:35:18

How to work with ASP.NET Core MVC cache?

I'm working with ASP.NET Core MVC, I've been trying to save 1 page size value in cache\cookies\session for 7 hours now.
in Startup added to the ConfigureServices method services.AddMemoryCache(); services.AddSession();
the configure method is like this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IMemoryCache cache)
        {
            
                if (env.IsDevelopment())
                {

                    app.UseDeveloperExceptionPage();
                    app.UseDatabaseErrorPage();
                }
                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.UseAuthentication();
                app.UseAuthorization();
            app.UseSession();
            
            cache.CreateEntry("_PageSize");
            cache.Set("_PageSize", 10);
            app.UseEndpoints(endpoints =>
            {
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                    endpoints.MapRazorPages();
                });
            });

         
        }


I tried to do something in the controller itself:
private IMemoryCache _cache;
        public int cacheEntry;
        public const string SessionKeyName = "_PageSize";
        public int ps;
        private readonly AppDbContext _context;
        //private readonly IHttpContextAccessor _httpContextAccessor;
       
        public ProductCategoriesController(AppDbContext context, IMemoryCache memoryCache)
        {
            
            _context = context;
            _cache = memoryCache;

            _cache.CreateEntry("_PageSize");
            var cacheB = _cache.TryGetValue("_PageSize", out cacheEntry);
            if (!cacheB)
            {
                _cache.Set("_PageSize", 10);
                
                ps = 10;
            }
            else ps = cacheEntry;

        }


To sense-zero, I look through the developer tools - nothing appears anywhere, even errors.
Something went wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Peter, 2021-01-26
@petermzg

https://docs.microsoft.com/en-us/aspnet/core/funda...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question