2
Reply

ASP.NET interview question :- How do we write a HttpModule ?

    using System;
    using System.Web;
    public class CustomHttpModule:IHttpModule 
    {
    public void Dispose() 
    {
    }
    public void Init(System.Web.HttpApplication Appl) 
    {
    Appl.BeginRequest += new System.EventHandler(OnBeginRequest);
    }
    public void OnBeginRequest(object sender, EventArgs e)
    {
    HttpApplication app = (HttpApplication)sender;
    app.Context.Response.Write("HttpModule says Hello!");
    }
    }
    in web.config file
    <httpModules>
    <add type="CustomHttpModule.Test" name="CustomHttpModule">
    </httpModules>

    Answer:
     

    Again a simple .NET Interview question Writing a HttpModule is a two step process.

    Create a class which implements IhttpModule. 

     
        public class clsHttpModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
           this.httpApp = context;
           httpApp.Context.Response.Clear();
           httpApp.AuthenticateRequest += new EventHandler(OnAuthentication);
           httpApp.AuthorizeRequest += new EventHandler(OnAuthorization);
      ....
      ....
      ....
      
        }
        void OnAuthorization(object sender, EventArgs a)
        {
            //Implementation
        }
        void OnAuthentication(object sender, EventArgs a)
        {      
            //Implementation
        }   
    }

     Make a entry in the web.config file.

       <httpModules>
    <add name="clsHttpModule" type="clsHttpModule"/>
    </httpModules>

     

    Do view my top .NET interview questions and answers