Jeff Norman
Jeff Norman

Reputation: 1044

How can I programmatically clear cache?

In my application (ASP.NET + c#) I need to clear the cache before a user enters an aspx page.

Does anybody have any idea how I can programmatically clear the cache on an aspx page, or in the code behind (c#)?

Upvotes: 4

Views: 57523

Answers (3)

to StackOverflow
to StackOverflow

Reputation: 124686

You can remove a page from the output cache as follows:

HttpResponse.RemoveOutputCacheItem("MyPage.aspx");

This won't remove it from any client-side cache, so if you want to use this technique you will probably want to disable client-side cache, e.g. by using the following directive in your aspx page:

<%@ OutputCache Location="Server" ...

Upvotes: 1

Massif
Massif

Reputation: 4433

Unless there's some javascript way to clear the cache (which would be awful), you can't.

Your best bet is to ensure the page doesn't get cached at all, by doing as Sukhi suggests - or setting up a no-cache cache profile and using the OutputCache directive.

Upvotes: 0

Sukhjeevan
Sukhjeevan

Reputation: 3156

Write following code in the page load event:

protected void Page_Load(object sender, EventArgs e)
{
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Cache.SetExpires(DateTime.Now);
    Response.Cache.SetNoServerCaching();
    Response.Cache.SetNoStore();
}

Upvotes: 14

Related Questions