Writing a Custom HTTP Handler

Every resource processed by ASP.NET is processed by an actor called an HTTP handler. For example, web pages with the extension .aspx are processed by a page handler, while stand-alone web services with the extension .asmx are processed by a SOAP handler. All these classes are implementations of the IHttpHandler interface.

When you associate your custom file type with the ASP.NET runtime, as shown in the previous section, you have to tell ASP.NET how to process this resource. The way to do this is to write a custom HTTP handler class that implements this interface. A custom handler processing any type of binary file looks like this:

Namespace RolesDemo.Handlers Public Class GenericHandler Implements IHttpHandler #Region "IHttpHandler Members"

Public Readonly Property IsReusable() As Boolean _ Implements IHttpHandler.IsReusable Get

Return True End Get End Property

Public Sub ProcessRequest(ByVal context As HttpContext) _ Implements IHttpHandler.ProcessRequest Dim ret As Byte() = Nothing

' Open the file specified in the context

Dim PhysicalPath As String = context.Server.MapPath _

(context.Request.Path) Using fs As New FileStream(PhysicalPath, FileMode.Open) ret = New Byte(fs.Length - l) {} fs.Read(ret, 0, Clnt(fs.Length)) End Using

' If it is not null, return the byte array If ret IsNot Nothing Then context.Response.BinaryWrite(ret) End If End Sub

#End Region End Class End Namespace

This handler simply determines the local physical path of the resource requested by calling Server.MapPath. Afterward it uses a FileStream for opening the resource and returning the bytes included for this resource. You have to configure this HTTP handler as well. For this purpose, you just add a <httpHandlers> section within the <system.web> section of your web. config application configuration, as follows:

<httpHandlers>

<add verb="GET,POST" path="*.txt"

type="RolesDemo.Handlers.GenericHandler"/> </httpHandlers>

The type attribute includes the full namespace and class name of the IHttpHandler implementation. Optionally, if it is placed in a different assembly, you have to specify the name of the assembly in the format "namespace.typename, assembly" within it. The additional attributes specify the HTTP verb (GET, PUT, POST, or * for all) as well as the path and file types for which the handler will be used.

+1 0

Average user rating: 5 stars out of 1 votes

Post a comment

  • Receive news updates via email from this site