How can I force browsers to reload cached CSS files when using Asp.Net Themes? [duplicate]

廉价感情. 提交于 2019-12-14 04:16:39

问题


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.


回答1:


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




回答2:


If you are asking how the SERVER side can force reloading... One way is to dynamically change the filename of the CSS/JS so that subsequent calls to the page require a different file.

<sarcasm> The other is to simply tell the user to press CTRL-F5 :) </sarcasm>




回答3:


When finished doing changes to the site change the name of the css manually.




回答4:


I've not found a way to version App_Themes files (yet), but you can set them to expire in a relatively short period of time (e.g., 10 seconds), which will minimize the cache problem while giving you some performance benefit of caching. Remember, if the file has not changed, the server will respond with 304-Not modified so traffic is reduced even if the browser requests the file.

Add this to the <configuration> section of the Web.Config

<location path="App_Themes">
    <system.webServer>
        <staticContent>
            <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:10" />
        </staticContent>
    </system.webServer>
</location>


来源:https://stackoverflow.com/questions/4736867/how-can-i-force-browsers-to-reload-cached-css-files-when-using-asp-net-themes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!