0

I create an IIS Module that appends text to the page before it loads. When I go to the URL, this works perfect the first time the page loads. On subsequent loads, however, the text is never appended.

Any thoughts on how to remedy this?

== CODE ==

Here's my web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <compilation debug="true" />
    </system.web>
    <system.webServer>
        <modules>
            <add name="MIModule" type="MI.MyModule, MI" />
        </modules>
        <caching enabled="false" enableKernelCache="false" />       
    </system.webServer>
</configuration>

Some module code:

public void context_PreRequestHandlerExecute(Object source, EventArgs e)
        {
            HttpApplication app = (HttpApplication)source;
            HttpRequest request = app.Context.Request;

            string pageContent = app.Response.Output.ToString();

            string useragent = "HI!<br />" + pageContent + "<hr />" ;

            try
            {
                _current.Response.Output.Write(useragent);
            }
            catch
            {
            }
        }

and the rest of the code:

private HttpContext _current = null;

        #region IHttpModule Members

        public void Dispose()
        {
            throw new Exception("Not implemented");
        }

        public void Init(HttpApplication context)
        {
            _current = context.Context;

            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        }

        #endregion
Dexter
  • 1,128
  • 3
  • 25
  • 51

1 Answers1

2

Is the _current variable actually HttpContext.Current? Is it a static field in your module? When/how is it initialized? My guess is that the empty catch clause gobbles up all errors, and following that thought, you most probably get a null reference on _current. Try removing the try/catch to learn more on what's wrong with your code

bottlenecked
  • 2,079
  • 2
  • 21
  • 32
  • you're right on, _current is null which is why that's happening. Not sure why it's null, any ideas as to how to fix it? – Dexter Jul 18 '11 at 18:12
  • well, you *do* have `HttpRequest request = app.Context.Request;`, you could just as easily write `var response = app.Context.Response;` and then `response.Output.Write(/*your thing*/)`. As to why it's null... it's probably set to null after the first request (when it's actually initialized and subsequently runs as normal) is completed, since HttpContext is created for each request anew (a request singleton). Although if someone else knows better, please feel free to correct me :) – bottlenecked Jul 18 '11 at 19:25