Injecting Content in an ASP.NET Web Forms Page From a Module
Modules are a great extensibility mechanism because they allow us to glimpse into a request and to do something before the response is sent back.
Sometimes, you may want to change the page – add some contents, change the properties of controls, etc. – in a module, so that you can reproduce the behavior for all (or some) pages in an easily reusable way. For that, ASP.NET offers a great number of events, that compose the request lifecycle.
Say you want to inject custom content to the page; you might be surprised to find that if even if you choose what appears to be a right event, the injected content does not show up!
Here’s the right way to do it: you need to hookup the Page’s Init event (PreInit won’t work) and do the change from there. For example:
1: public class InjectModule : IHttpModule
2: {
3: #region IHttpModule Members
4:
5: public void Dispose() {}
6:
7: public void Init(HttpApplication context)
8: {
9: context.PreRequestHandlerExecute += this.OnPreRequestHandlerExecute;
10: }
11:
12: private void OnPreRequestHandlerExecute(Object sender, EventArgs e)
13: {
14: var app = sender as HttpApplication;
15:
16: if ((app != null) && (app.Context != null))
17: {
18: var page = app.Context.CurrentHandler as Page;
19:
20: if (page != null)
21: {
22: page.Init += (s, args) =>
23: {
24: var p = (s as Page);
25:
26: if (p.Header != null)
27: {
28: p.Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">window.alert('Hello, World!')</script>"));
29: }
30:
31: if (p.Form != null)
32: {
33: p.Form.Controls.Add(new LiteralControl("Hello, World!"));
34: }
35: };
36: }
37: }
38: }
39:
40: #endregion
41: }
I am using the PreRequestHandlerExecute event because here the page is already built and the CurrentHandler property because of any possible transfers.