开发者

Prevent page from being cached when using OutputCacheAttribute

Is there a way to prevent a page from being cached based on some logic?

I want to cache anonymous access to a page, so I can set VaryByCustom="user" and have some magic in Global.asax's GetVaryByCustomString method. Ok. But I don't actually want to cache the page if the user's authenticated, only if it's not authenticated. Is there a 开发者_StackOverflowway to specify this kind of thing?

The reason I want the data to not be added to the cache to begin with (instead of added with some random key) is that as the cache grows things get thrown out and I don't want the non-authenticated version to get thrown out.


You can carry this out programmatically in your page load in asp.net web forms.

bool isAuthenticated = /*variable assignment*/;
if (isAuthenticated){
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
}

If you want this logic in a seperate method somewhere you can register a callback like so.

Response.Cache.AddValidationCallback(new HttpCacheValidateHandler(MethodWhichSetsCacheability), null);

In MVC you should be able to execute the above code in your controller


You can check whether the user is authenticated in GetVaryByCustomString.

context.Request.IsAuthenticated

If true return the null. If not return a fixed string.

The base implementation of GetVaryByCustomString returns null, so this should be safe. But since null can't be used as a key in the cache then I think this page won't get cached.

However I haven't tested this!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜