Creating Custom HTTP Modules : HTTP Modules « Development « ASP.NET Tutorial






An HTTP Module is a .NET class that executes with each and every page request. 

The HTTP Module doesn't allow you to request a page unless you include the proper query string with the request. 

File: App_Code\QueryStringAuthenticationModule.cs

using System;
using System.Web;

namespace MyNamespace
{
    public class QueryStringAuthenticationModule : IHttpModule
    {
        public void Init(HttpApplication app)
        {
            app.AuthorizeRequest += new EventHandler(AuthorizeRequest);
        }

        private void AuthorizeRequest(Object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context;

            string path = context.Request.AppRelativeCurrentExecutionFilePath;
            if (String.Compare(path, "~/login.aspx", true) == 0)
                return;

            bool authenticated = false;
            if (context.Request.QueryString["password"] != null)
            {
                if (context.Request.QueryString["password"] == "secret")
                    authenticated = true;
            }

            if (!authenticated)
                context.Response.Redirect("~/Login.aspx");
        }

        public void Dispose() { }
    }
}

            
Register the HTTP Module in the web configuration file. 
File: Web.Config

<configuration>
    <system.web>

      <httpModules>
        <add name="QueryStringAuthenticationModule"
             type="MyNamespace.QueryStringAuthenticationModule"/>
      </httpModules>

    </system.web>
</configuration>








9.25.HTTP Modules
9.25.1.Creating Custom HTTP Modules
9.25.2.HttpContext (C#)
9.25.3.HttpContext (VB)
9.25.4.URL rewriting HttpModule (C#)
9.25.5.URL rewriting HttpModule (VB)
9.25.6.The IHttpHandler page template (C#)
9.25.7.The IHttpHandler page template (VB)
9.25.8.Outputting an image from an HttpHandler (C#)
9.25.9.Outputting an image from an HttpHandler (VB)
9.25.10.Adding the HttpHandler configuration information to web.config
9.25.11.HttpModule Tester