Answer the question
In order to leave comments, you need to log in
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();
});
});
}
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;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question