我想让HttpModule从一些简单的配置数据中注入javascripts,css链接到HEAD元素.我不确定应该挂哪个事件?
我可以使用@H_301_3@ – context.PreRequestHandlerExecute用于动态更改母版页@H_301_3@ – 用于SEO优化的Context.BeginRequest
在HTTPModule Event Execution Order?有一些帮助
谢谢你的提示.干杯,X.
解决方法
这是我在没有HttpModule的情况下实现你正在做的事情的方法.我不喜欢httpmodule的想法,因为如果我忘记注册它并且它没有运行,我的应用程序将无法工作,这将是一个非常明显的错误.该页面绝对需要包含JS,因此我决定将其放在项目的基本Page类中.
我在几年前实现了,并希望能够包含更多脚本,它支持css,元标记等….我忘了为什么我使用Page.Header.Controls.Add而不仅仅是Page.ClientScript.RegisterClientScriptInclude但是有一个原因.
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; namespace YourNamespace { public class HeaderIncludesManager { private List<string> m_IncludedFiles = new List<string>(); public void IncludeScript(string s) { IncludeScript(s,null); } public bool IsIncluded(string file) { return (m_IncludedFiles.Find(s => s.Equals(file,StringComparison.InvariantCultureIgnoreCase)) != null); } public void IncludeScript(string script,string condition) { Page page = HttpContext.Current.CurrentHandler as Page; if (!IsIncluded(script) || page == null) return; string scriptFile = string.Format("/{0}/{1}?v={2}",MyConfig.JSDir,script,MyConfig.BuildNumber); if (page.Header != null) { string scriptTag = String.Format("<script language=\"javascript\" type=\"text/javascript\" src=\"{0}\"></script>\n",scriptFile); if (!String.IsNullOrEmpty(condition)) scriptTag = String.Format("<!--[{0}]><script language=\"javascript\" type=\"text/javascript\" src=\"{1}\"></script><![endif]-->\n",condition,scriptFile); page.Header.Controls.Add(new LiteralControl(scriptTag)); m_IncludedFiles.Add(script); } else if (!page.ClientScript.IsClientScriptIncludeRegistered(GetType(),scriptFile)) { page.ClientScript.RegisterClientScriptInclude(GetType(),scriptFile,scriptFile); m_IncludedFiles.Add(script); } } public void IncludeCss(string css) { Page page = HttpContext.Current.CurrentHandler as Page; if (!IsIncluded(css) || page == null) return; string cssfile = string.Format("/{0}/{1}?v={2}",MyConfig.CssDir,css,MyConfig.BuildNumber); if (page.Header != null) { ((Page)HttpContext.Current.CurrentHandler).Header.Controls.Add(new LiteralControl(String.Format("<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />\n",cssfile))); m_IncludedFiles.Add(css); } } public void IncludeJQuery() { IncludeScript("jquery-1.2.3.min.js"); } public void IncludeJQueryUI() { IncludeJQuery(); IncludeScript("jquery.ui.1.0.min.js"); IncludeCss("jquery-theme.css"); } public void IncludeFlotScripts() { IncludeJQuery(); IncludeScript("flot/jquery.flot.js"); IncludeScript("flot/excanvas.pack.js","if IE"); } } public class MyPage : Page { public HeaderIncludesManager HeaderIncludes = new HeaderIncludesManager(); } public class MyControl : UserControl { public new MyPage Page { get { return (MyPage)base.Page; } } } public class SomeControlThatNeedsScripts : MyControl { protected override void OnLoad(EventArgs e) { Page.HeaderIncludes.IncludeJQueryUI(); base.OnLoad(e); } } }