Conditionally add OutputCache Directive

2019-07-28 23:28发布

I'm using the OutputCache directive in my aspx pages. I would like to add it or remove it based on the environment. For example, have the directive for production, but not development environments.

An if statement on the page doesn't seem to work:

<% if (someCondition) { %>
  <%@ OutputCache Location="Any" Duration="1800" VaryByParam="None" %>
<% } %>

Is there a way to remove (or add) a directive in the code behind? What's the best way to accomplish this?

1条回答
贼婆χ
2楼-- · 2019-07-29 00:10

Every OutputCache attribute can be handled programmatically as shown here: How to cache in ASP.NET by using Visual C# .NET

Is there a way to remove (or add) a directive in the code behind?

Not that I have seen so far but not excluding the possibility. Nevertheless you would not have to as you have Response.Cache at your disposal for your scenario which gives you the whole ten yards to play with.

Although if you are using ASP.NET MVC, then you can use it as attributes as shown here: OutputCacheAttribute Class ([OutputCache(CacheProfile = "MyProfile", Duration = 10)]). There is a stackoverflow example as well here.

What's the best way to accomplish this?

Using Response.Cache. Check the code below.

using System.Web;

//......
//......
//......

if (someCondition) 
{
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public); //Location="Any"
HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddSeconds(1800)); //Duration="1800"
HttpContext.Current.Response.Cache.SetValidUntilExpires(true); 
}
查看更多
登录 后发表回答