views:

479

answers:

2

The HttpModule works fine ("hello" is replaced with "hello world") but for some reasons images on the WebForms are not displayed when the module is added to the Web.config. When the module is removed from the Web.config, images on the WebForms are displayed.

Does anyone know why?

The HTML that is produced with or without the HttpModule is exactly the same!

//The HttpModule

public class MyModule : IHttpModule
{
        #region IHttpModule Members

        public void Dispose()
        {
            //Empty
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(OnBeginRequest);
            application = context;
        }

        #endregion

        void OnBeginRequest(object sender, EventArgs e)
        {
            application.Response.Filter = new MyStream(application.Response.Filter);
        }
}

//The filter - replace "hello" with "hello world"

public class MyStream : MemoryStream
{
        private Stream outputStream = null;

        public MyStream(Stream output)
        {
            outputStream = output;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {

            string bufferContent = UTF8Encoding.UTF8.GetString(buffer);
            bufferContent = bufferContent.Replace("hello", "hello world");
            outputStream.Write(UTF8Encoding.UTF8.GetBytes(bufferContent), offset, UTF8Encoding.UTF8.GetByteCount(bufferContent));

            base.Write(buffer, offset, count);
        }
}
+2  A: 

Try doing this, this will only install filter for aspx pages, and all other urls will work fine.

void OnBeginRequest(object sender, EventArgs e)    
{
     if(Request.Url.ToString().Contains(".aspx"))        
         application.Response.Filter = new MyStream(application.Response.Filter);    
}

There are several properties, you must try to use Response.Url.AbsolutePath or some other code that will give perfect result.

Akash Kava
Thanks! Your code suggestion works.
hungster
+2  A: 

Are you applying the module to all requests? You shouldn't, as it will mess up anything that's binary. You could potentially just make your event handler only apply the filter when the content type is appropriate.

It would be better only to apply the module to particular extensions to start with though.

To be honest, your stream implementation is slightly dodgy too - it may well fail for characters which take up multiple bytes when encoded in UTF-8, and you're decoding the whole buffer even when only part of it is written. Additionally, you might get "hello" split up as "he" and then "llo" which you don't currently cope with.

Jon Skeet
Making the event handler applying the filter on .aspx pages only did it. Thanks for the help.
hungster