Saturday, February 9, 2019

HTTPHanlder and HTTPModule

When a client makes a request for a resource located on the server in an ASP.NET application, each request is handled by the HTTP Handlers. Microsoft ASP.NET has number of built-in HTTP Handlers which serves different files like .ASPX, .ASMX etc. Based on the extension of the file, the appropriate HTTP Handlers gets loaded which is mapped to the extension and is responsible for processing the ASP.NET request.


Custom HttpHandlers
public class CustomHandler:IHttpHandler
{
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.Write("<h1 style='Color:#000066'>WelCome To Custom HttpHandler</h1>");
        context.Response.Write("HttpHandler processed on - " + DateTime.Now.ToString());
        using (StreamWriter SW=new StreamWriter(@"E:\HandlerMessages.txt",true))
        {
            SW.WriteLine("The message date time is - " + DateTime.Now.ToString());
            SW.Close();
        }
    }
}

<httpHandlers>
        <add verb="*" path="*.curry" type="CustomHandlerModuleExample.CustomHandler"/>
</httpHandlers>


HttpModule

HttpModule is another part of request processing of ASP.NET. In a single request processing, there can be more than one modules which gets executed. HttpModules take part in processing of the request by handling the Application events. There are number of events which you can handle during the HttpModule processing. For example - BeginRequest(), EndRequest(), AuthenticateRequest() etc.
 IHttpModule interface. This interface provides two method
Init()
Dispose()


public class CustomHttpModule:IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(this.context_BeginRequest);
        context.EndRequest += new EventHandler(this.context_EndRequest);
    }
    public void context_EndRequest(object sender, EventArgs e)
    {
        StreamWriter sw = new StreamWriter(@"C:\requestLog.txt", true);
        sw.WriteLine("End Request called at " + DateTime.Now.ToString());
        sw.Close();
    }
    public void context_BeginRequest(object sender, EventArgs e)
    {
        StreamWriter sw = new StreamWriter(@"C:\requestLog.txt", true);
        sw.WriteLine("Begin request called at " + DateTime.Now.ToString());
        sw.Close();
    }
    public void Dispose()
    {

    }
}

<httpModules>
      <add name="DotNetCurryModule" type="CustomHttpModule"/>
</httpModules>

No comments:

Post a Comment

Asp.net Core Continued

65 66 67 68 69 70 71 65 ASP.NET Core Identity It is a membership system Step 1 : Inherit from IdentityDbContext class instead of ...