试过这样的事情:
HttpApplication app = s as HttpApplication; //s is sender of the OnBeginRequest event System.Web.UI.Page p = (System.Web.UI.Page)app.Context.Handler; System.Web.UI.WebControls.Label lbl = new System.Web.UI.WebControls.Label(); lbl.Text = "TEST TEST TEST"; p.Controls.Add(lbl);
运行时,我得到"对象引用未设置为对象的实例".为最后一行......
如何在原始文件中的特定loactions处插入两行文本(asp.net/html)?我怎么弄清楚文件的扩展名(我只想在aspx文件上应用这个...?
它比你想象的简单:
public void Init(HttpApplication app) { app.PreRequestHandlerExecute += OnPreRequestHandlerExecute; } private void OnPreRequestHandlerExecute(object sender, EventArgs args) { HttpApplication app = sender as HttpApplication; if (app != null) { Page page = app.Context.Handler as Page; if (page != null) { page.PreRender += OnPreRender; } } } private void OnPreRender(object sender, EventArgs args) { Page page = sender as Page; if (page != null) { page.Controls.Clear(); // Or do whatever u want with ur page... } }
如果PreRender事件不够,你可以在PreRequestHandlerExecute EventHandler中添加你需要的任何事件......