How can I grab the response text of web page via IIS Module?

246 views Asked by At

I'm working on an IIS module that, when a web page request is made, it looks over the data being passed back to the browser and replaces certain keywords with approved keywords. I realize there are multiple ways to do this, but for our purposes an IIS module will work best.

How can I read the stream of data being send back to the browser into a string so that I can convert keywords as needed?

Any help would be GREATLY appreciated!

Here's the code:

namespace MyNamespace
{
    class MyModule : IHttpModule
    {
        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

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

There are 1 answers

0
Madhur Ahuja On BEST ANSWER

There are two ways:

  1. Using Response Filters

https://web.archive.org/web/20211029043851/https://www.4guysfromrolla.com/articles/120308-1.aspx

  1. Handle the PreRequestHandlerExecute event of the application as it is run just before the IHttpHandler processes the page itself:

    public class NoIndexHttpModule : IHttpModule
    {
      public void Dispose() { }
    
      public void Init(HttpApplication context)
      {
        context.PreRequestHandlerExecute += AttachNoIndexMeta;
      }
    
      private void AttachNoIndexMeta(object sender, EventArgs e)
      {
        var page = HttpContext.Current.CurrentHandler as Page;
        if (page != null && page.Header != null)
        {
          page.Header.Controls.Add(new LiteralControl("<meta name=\"robots\" value=\"noindex, follow\" />"));
        }
      }
    

    }