Tags: | Categories: Blog Posted by admin on 3/9/2009 5:54 PM | Comments (4)

Http Modules in ASP.NET 2.0 makes live so easy to separate the HTTP layer from the UI. You can add as many HTTP Modules as you require or add modules inside only one HTTP Module. Useful ones are:

 

Compressing the response back to the browser. When using IIS 5 this is a great module to add in all your solutions.

Easy URL paths. Used by forums.asp.net.

Installing a new Session Manager, copywriter notice, etc …

 

This is the skeleton of an HTTP. As you can see you need to inherited from IHttpModule so will create the functions Dispose() and void Init(HttpApplication context); for you.

 

 

Lets look at a compression HttpModule:

 

class AlHttpModule : IHttpModule

    {

 

        public AlHttpModule()

        {

 

        }

 

        #region IHttpModule Members

 

 

        public void Dispose()

        {

            // Clean any resources you may used

        }

 

        public void Init(HttpApplication context)

        {

            context.BeginRequest += new EventHandler(context_BeginRequest);

        }

 

        #endregion

 

        public void context_BeginRequest(object sender, EventArgs e)

        {

            HttpApplication app = (HttpApplication)sender;

 

            string encodings = app.Request.Headers.Get("Accept-Encoding");

 

            // No encodings stop the HTTP Module processing

            if (encodings == null)

                return;

 

            if (app.Request.Url.AbsolutePath.IndexOf(".aspx") == -1 &&

                app.Request.Url.AbsolutePath.IndexOf(".asmx") == -1 )

                return;

 

            Stream baseStream = app.Response.Filter;

 

            encodings = encodings.ToLower();

 

            if (encodings.Contains("gzip"))

            {

                app.Response.Filter = new GZipStream(baseStream, CompressionMode.Compress);

                app.Response.AppendHeader("Content-Encoding", "gzip");

            }

            else if (encodings.Contains("deflate"))

            {

                app.Response.Filter = new DeflateStream(baseStream, CompressionMode.Compress);

                app.Response.AppendHeader("Content-Encoding", "deflate");

            }

        }

    }

 

 

As you can see .Request.Url.AbsolutePath is where everything happens. You can create a simple easy URL path like used by http://forums.asp.net by just looking at Request.Url.AbsolutePath and using Server.Transfer() to the right page. So people can browser to http://domain.com/1244 and you can convert that to Server.Transfer(“http://domain.com/Page.aspx?id=1244”);

 

Cheers

Al

blog comments powered by Disqus