使用 OutputCacheAttribute 时防止页面被缓存

发布于 2024-10-01 19:27:10 字数 285 浏览 0 评论 0原文

有没有办法根据某种逻辑阻止页面被缓存?

我想缓存对页面的匿名访问,因此我可以设置 VaryByCustom="user" 并在 Global.asax 的 GetVaryByCustomString 方法中发挥一些作用。好的。但我实际上不想在用户经过身份验证的情况下缓存页面,只有在未经过身份验证的情况下才缓存页面。有没有办法指定这种事情?

我希望数据不首先添加到缓存中(而不是添加一些随机密钥)的原因是,随着缓存的增长,数据会被丢弃,而我不希望未经身份验证的版本被丢弃。

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 way 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

洋洋洒洒 2024-10-08 19:27:10

您可以在 ASP.NET Web 表单的页面加载中以编程方式执行此操作。

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

如果您希望在某个单独的方法中使用此逻辑,您可以像这样注册回调。

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

在 MVC 中,您应该能够在控制器中执行上述代码

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

半﹌身腐败 2024-10-08 19:27:10

您可以在 GetVaryByCustomString 中检查用户是否已通过身份验证。

context.Request.IsAuthenticated

如果为 true,则返回 null。如果没有返回固定字符串。

GetVaryByCustomString 的基本实现返回 null,因此这应该是安全的。但由于 null 不能用作缓存中的键,所以我认为该页面不会被缓存。

不过我还没有测试过这个!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文