Can I force a refresh of my stylesheet file?

前端 未结 12 2233
-上瘾入骨i
-上瘾入骨i 2020-12-13 18:51

I have just spent half a day quietly going mad.

I\'m making changes to my classes in the Site.css file and they were not being reflected in the site being develope

12条回答
  •  不知归路
    2020-12-13 19:45

    To further Ian Kemp's answer which utilises the LastWriteTime of the style sheet in question, I have written an MVC helper to output the tag with the cache-busting parameter built in.

    The Code

    public static class CssLinkHelper
    {
        public static IHtmlString StyleSheet(this HtmlHelper helper, string stylesheetname)
        {
            // define the virtual path to the css file (see note below)
            var virtualpath = "~/" + stylesheetname;
            // get the real path to the css file
            var realpath = HostingEnvironment.MapPath(virtualpath);
            // get the file info of the css file
            var fileinfo = new FileInfo(realpath);
    
            // create a full (virtual) path to the css file including a cache busting parameter (e.g. /main.css?12345678)
            var outputpath = VirtualPathUtility.ToAbsolute(virtualpath) + "?" + fileinfo.LastWriteTime.ToFileTime();
            // define the link tag for the style sheet
            var tagdefinition = string.Format("", outputpath);
    
            // return html string of the tag
            return new HtmlString(tagdefinition);
        }
    }
    

    Usage

    @Html.StyleSheet("main.css")
    

    Output

    
    

    Note

    In case you're wondering about the var virtualpath = "/~" + ... part and thinking, why not just pass it in as "~/main.css"? I have implemented this function this way because all my css files are in a common folder (/assets) and the helper will prefix my output with the common folder name i.e. /assets/main.css?131393346850223541

提交回复
热议问题