Add url parameter to css file in asp themes folder

有些话、适合烂在心里 提交于 2019-12-01 02:31:32

问题


I have written a bit of code that helps with versioning of js files. Essentially it spins around the current script manager and appends the javascript file path with an md5 hash of the file. So

<script src="../Javascript/Navigation.js" type="text/javascript"></script>

becomes

<script src="../Javascript/Navigation.js?md5=70D2B4D1F236C7E340D9152B9E4102C3" type="text/javascript"></script>

I think this is a fairly common thing to do (or variants of it). What I am struggling to do is pick up the css files in the app_themes folder and do the same.

How do I get in and change the css links?


回答1:


You can use a control adapter to neatly inject this behavior into the page as follows:

public class PageAdapter : System.Web.UI.Adapters.PageAdapter
{
    protected override void OnPreRender(System.EventArgs e)
    {
        foreach (var link in Page.Header.Controls.OfType<HtmlLink>().ToList())
            if (link.Attributes["type"].Equals("text/css", StringComparison.OrdinalIgnoreCase))
                if (link.Attributes["href"].Contains("/App_Themes/{0}/".Fill(Page.Theme), StringComparison.OrdinalIgnoreCase))
                   /* process link */

        base.OnPreRender(e);
    }
}

You can plug it in by saving the following as a *.browser file in the App_Browsers folder:

<browsers>
  <browser refID="Default">
    <controlAdapters>
      <adapter controlType="System.Web.UI.Page"
               adapterType="PageAdapter" />
    </controlAdapters>
  </browser>
</browsers>

Overall, I think Control Adapters are a powerful AOP-like mechanism for injecting behavior into control/page life-cycles; they are almost entirely ignored in favor of traditional sub-classing.




回答2:


I am facing one issue that it is repeating css entry in html markup on every postback. for example, I have newabc.css. the code will change it to newabc.css?v=1. if I see html source after 5 postback, it will have 5 "newabc.css?v=1". so I added link.EnableViewState = False, it works fine but is it actually needed?

    Dim link As HtmlLink = Nothing

    For Each c As Control In Page.Header.Controls
        If TypeOf c Is HtmlLink Then
            link = TryCast(c, HtmlLink)

            If link.Href.IndexOf("App_Themes/", StringComparison.InvariantCultureIgnoreCase) >= 0 AndAlso link.Href.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase) Then
                link.Href &= "?v=" & VER_CSS
                'link.EnableViewState = False
            End If
        End If
    Next



回答3:


Avoid to invent the wheel twice by using Combres instead. Does everything you ask for, and more!



来源:https://stackoverflow.com/questions/2019807/add-url-parameter-to-css-file-in-asp-themes-folder

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