且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我怎么能强迫浏览器重新加载缓存的CSS文件使用Asp.Net的主题是什么时候?

更新时间:2023-09-01 08:48:10

我觉得我有一个快速和肮脏的解决方案。关键是要检查页头中的控件(例如在 preRender 相),找到 App_Themes文件文件夹,并让它们能动态(通过添加一些随机信息到查询字符串)。这很可能会告诉浏览器无效的文件的缓存版本。

在code:

 保护无效Page_ preRender(对象发件人,EventArgs的发送)
{
    HtmlLink链接= NULL;    的foreach(在Header.Controls控制C)
    {
        如果(c是HtmlLink)
        {
            链接= C作为HtmlLink;            如果(link.Href.IndexOf(App_Themes文件/,StringComparison.InvariantCultureIgnoreCase)GT; = 0&放大器;&放大器;
                link.Href.EndsWith(CSS,StringComparison.InvariantCultureIgnoreCase))
            {
                link.Href + =的String.Format(,DateTime.Now.Ticks.ToString()T = {0}?);
            }
        }
    }
}

输出:

 <链接HREF =?App_Themes文件/ MyTheme的/ MyTheme.css T = 634310637798128189
        类型=文/ CSS的rel =stylesheet属性/>

请注意,你需要有一个<头=服务器> 在你的页面的标记中声明,以便能够访问标题属性(否则将)。

Possible Duplicate:
CSS in App_Theme folder gets Cached in Browser

I've seen "What is an elegant way to force browsers to reload cached CSS/JS files?" but the answer there uses PHP and it doesn't address the fact that the CSS is injected dynamically by an ASP.Net Theme.

I think I have a quick and dirty solution. The trick is to examine the controls within the page header (for example in the PreRender phase), find the links pointing to CSS-files under the App_Themes folder and make them dynamic (by adding some random information to the query-string). This will most likely tell the browser to invalidate the cached version of the file.

The code:

protected void Page_PreRender(object sender, EventArgs e)
{
    HtmlLink link = null;

    foreach (Control c in Header.Controls)
    {
        if (c is HtmlLink)
        {
            link = c as HtmlLink;

            if (link.Href.IndexOf("App_Themes/", StringComparison.InvariantCultureIgnoreCase) >= 0 &&
                link.Href.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase))
            {
                link.Href += string.Format("?t={0}", DateTime.Now.Ticks.ToString());
            }
        }
    }
}

The output:

    <link href="App_Themes/MyTheme/MyTheme.css?t=634310637798128189" 
        type="text/css" rel="stylesheet" />

Note that you need to have a <head runat="server"> declared in your page's markup in order to be able to access the Header property (otherwise it will be null).