Clearing Page Cache in ASP.NET

Clearing Page Cache in ASP.NET

I've found the answer I was looking for:

HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx");

How to clear the server cache in iis

Both clear the cache.
Recycling an App Pool is just less drastic, as it continues to process already received requests and cycles after that. This can be done under load - never had issues with it.

ASP.NET Clear Cache

is it possible to Clear a certain page
from the Cache?

Yes:

HttpResponse.RemoveOutputCacheItem("/pages/default.aspx");

You can also use Cache dependencies to remove pages from the Cache:

this.Response.AddCacheItemDependency("key");

After making that call, if you modify Cache["key"], it will cause the page to be removed from the Cache.

In case it might help, I cover caching in detail in my book: Ultra-Fast ASP.NET.

Asp.Net Cache is cleared when reentering the page

Check the database you use for cache, my first guess is that nothing is actually stored.

With IoC, the proper setup would look something in the lines of adding a distributed cache to services

services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = _config["SQLDataProvider_Cache"];
options.SchemaName = "dbo";
options.TableName = "TestCache";
});

There are two types of cache policies you can use:

  • (DateTimeOffSet) CacheItemPolicy.AbsoluteExpiration expires after fixed time from initial set

  • (DateTimeOffSet) CacheItemPolicy.SlidingExpiration expires after fixed time from last access

Typically you would want to use the SlidingExpiration one, but as you define absolute then registration would

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
IApplicationLifetime lifetime, IDistributedCache cache)
{
lifetime.ApplicationStarted.Register(() =>
{
var currentTimeUTC = DateTime.UtcNow.ToString();
var encodedCurrentTimeUTC = Encoding.UTF8.GetBytes(currentTimeUTC);
var options = new DistributedCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromHours(1));
cache.Set("cachedTimeUTC", encodedCurrentTimeUTC, options);
});

The repository itself should not contain static members (or only logger). Adding an interface for this repository would improve testing and mocking out features as well as being default way to pass this with IoC

public class ReportRepository : IReportRepository
{
    private readonly IAppCache _cache;
    private readonly ILogger _logger;
    private SomeService _service;

public string ServiceUrl { get; set; }
public string RequestUri { get; set; }
 
    public ReportRepository(IAppCache appCache, ILogger<ShowDatabase> logger, SomeService service)
    {
        _service = service;
        _logger = logger;
        _cache = appCache;
    }
 
    public async Task<List<Show>> GetShows()
    {   
var cacheKey = "kpi_{companyID}_{fromYear}_{fromMonth}_{toYear}_{toMonth}_{locationIDs}";
        Func<Task<List<DataSet>>> reportFactory = () => PopulateReportCache();
//if you do it in DistributedCacheEntryOptions you do not need to set it here
var absoluteExpiration = DateTimeOffset.Now.AddHours(1);
        var result = await _cache.GetOrAddAsync(cacheKey, reportFactory, absoluteExpiration);
        return result;
    }
  
    private async Task<List<DataSet>> PopulateReportCache()
    {
        List<DataSet> reports = await _service.GetData(ServiceUrl, RequestUri, out result);
        _logger.LogInformation($"Loaded {reports.Count} report(s)");
        return reports.ToList(); //I would have guessed it returns out parameter result ...
    }
}

For more info check Cache in-memory in ASP.NET Core.



Edit

In .net 4.5 use LazyCache

var cache = new CachingService();
var cachedResults = cache.GetOrAdd(key, () => SetMethod());

to use sql server, mysql, postgres, etc then just implement ObjectCache and pass it to the constructor of the caching service. Here is a guide that also list few more common ones like Redis. It defaults to 20 minutes sliding expiration and you can set it by changing the policy.

How to clear browser cache when user log off in asp.net using c#?

I think you are almost there. You need more HTML headers to support all browsers. According to this article on SO these are the ones that work on all browsers:

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0

The full code for this is:

HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
HttpContext.Current.Response.AddHeader("Pragma", "no-cache");
HttpContext.Current.Response.AddHeader("Expires", "0");


Related Topics



Leave a reply



Submit