【问题标题】:Accessing ScriptManager proxies in code在代码中访问 ScriptManager 代理
【发布时间】:2010-11-21 10:29:31
【问题描述】:

我有一种情况,我想在我的 ScriptManager(包含在我的 MasterPage 中)中引用的 js 文件(例如“custom.js?2009082020091417”)的路径中添加“上次修改”时间戳并在任何 ScriptManagerProxies(内容页面)中。

我可以轻松地在代码中访问 ScriptManager,然后遍历它的 Scripts 集合以获取我以声明方式设置的脚本路径,然后“设置”一个带有“?[lastmodifiedtimestamp]”的新路径。

问题是,我不知道如何访问可能存在的任何 ScriptManagerProxies。

调试时,我可以看到非公共成员(._proxies)中的代理。我浏览了文档,但看不到您可以在哪里实际公开访问此集合。

我错过了什么吗?

我的内容页面的 Page_PreRenderComplete 事件的基类中有以下代码:

ScriptManager sm = ScriptManager.GetCurrent((Page)this);
if(sm != null)
{
     foreach (ScriptReference sr in sm.Scripts)
     {
         string fullpath = Server.MapPath(sr.Path);
         sr.PathWithVersion(fullpath); //extension method that sets "new" script path
     }
}

上面的代码提供了我在 MasterPage 中定义的一个脚本,但没有提供我在内容页面的 ScriptManagerProxy 中定义的另外两个脚本。

【问题讨论】:

    标签: asp.net javascript asp.net-ajax auto-versioning


    【解决方案1】:

    想出了一个解决方案。似乎可以访问所有合并脚本的唯一位置是在主 ScriptManager 的 ResolveScriptReference 事件中。在这种情况下,对于具有已定义路径的每个脚本,我使用一种扩展方法,该方法将根据 js 文件的最后修改日期附加“版本号”。现在我的 js 文件是“版本化”的,当我对 js 文件进行更改时,浏览器不会缓存旧版本。

    母版页代码:

     protected void scriptManager_ResolveScriptReference(object sender, ScriptReferenceEventArgs e)
     {
        if (!String.IsNullOrEmpty(e.Script.Path))
        {
            e.AddVersionToScriptPath(Server.MapPath(e.Script.Path));
        }
     }
    

    扩展方法:

     public static void AddVersionToScriptPath(this ScriptReferenceEventArgs scrArg, string fullpath)
     {
           string scriptpath = scrArg.Script.Path;
    
           if (File.Exists(fullpath))
           {
               FileInfo fi = new FileInfo(fullpath);
               scriptpath += "?" + fi.LastWriteTime.ToString("yyyyMMddhhmm");
           }
    
           scrArg.Script.Path = scriptpath;
     }
    

    【讨论】:

    • 像 JS 的魅力一样工作,但是如何(将?)处理与 Javascript 相关联的 WebResource 文件(例如 CSS、图像等)?
    猜你喜欢
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    相关资源
    最近更新 更多