Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Customized Text Document .NET HTTP Handler

0.00/5 (No votes)
15 Sep 2002 1  
Customized text document .NET HTTP handler to process text file not with standard extensions, like .aaa, .xxx.

Introduction

This example provides simple high performance .NET HTTP customized handler to process text document browsing request. In many cases web sites need to handle text documents without standard extension, *.txt, but IIS cannot recognize such text files and give much trouble to us! This simple HTTP text documents handler can read the file with nonstandard extensions, with asynchronous IO.

Step 1

Create the HTTP handler program by implementing the HTTP handler interface IHttpHandler:

using System ;
using System.IO ;
using System.Web ;
using System.Text ; 

namespace Matthew.Utility
{

 public class FileHandler : IHttpHandler {


  private const int RD_BUFFER_SIZE = 4*1024 ;
  private HttpResponse Response ;
  private HttpRequest Request ;


  // State for Async read

  public class StateObject {
     public byte[] bs ;
     public FileStream fs ;
  }

  public void ProcessRequest(HttpContext ctx) {

    Response = ctx.Response ;
    Request = ctx.Request ;

    String Filename = Request.FilePath ;

    if ( Filename != null ) {

        Filename = Request.MapPath(Filename) ;
        FileStream fs = null ;

        try {
            fs = File.Open(Filename , 
              FileMode.Open, FileAccess.Read, FileShare.Read) ;
        }
        catch (  FileNotFoundException  ) {
            Response.Write("<html><body><h2>File <i>" + 
                Request.FilePath + 
                "</i> not exists!</h2></body></html>" ) ;
            return ;
        }

        StateObject stateObject = new StateObject() ;

        stateObject.fs = fs ;
        stateObject.bs = new byte[RD_BUFFER_SIZE] ;

        //  Set the content type as the browser need to know

        // how to display the content bases on its type

        Response.ContentType = "Text/plain" ;

        // Begin Async file read

         fs.BeginRead( stateObject.bs, 0, RD_BUFFER_SIZE, 
           new AsyncCallback(this.ReadCallback), stateObject );

    }
  } // void ProcessRequest(HttpContext ctx)



  public bool IsReusable { get { return true ; } }


  public void ReadCallback(IAsyncResult asyncResult)  {

    StateObject stateObject = (StateObject) asyncResult.AsyncState;

    FileStream fs = stateObject.fs;//(Stream) asyncResult.AsyncObject;


    int bytesRead = fs.EndRead(asyncResult);

    // Stream only return zero (0) at the end of the stream

    if ( bytesRead != 0 )  {  
        Response.BinaryWrite(stateObject.bs) ;
          fs.BeginRead( stateObject.bs, 0, RD_BUFFER_SIZE, 
            new AsyncCallback(this.ReadCallback), stateObject );
    }
    else {
           fs.Close() ;
    }

  }


 } // Class

} // namespace

And compile the program to the /bin subdirectory of the web application virtual directory.

Step 2

Amend the .NET application configuration file web.config in the web application virtual directory as follows:

<configuration>
    <system.web>
    <httpHandlers>
        <add verb="*" path="*.aaa" 
          type="Matthew.Utility.FileHandler,TextDocHandler" />
    </httpHandlers>
    </system.web>   
</configuration>

In this example, the file extension .aaa is opted to be handled by class Matthew.Utility.FileHandler in assembly TextDocHandler.

Step 3

Add the application mapping for your intended text file extension .aaa to IIS meta database in order to inform IIS service to pipe requests to .NET, whenever it received such file extension's in the URL path. In my case the .NET library is H:\WINNT\Microsoft.NET\Framework\v1.0.3705\aspnet_isapi.dll and you must map your file extension to your .NET module which maybe different from my module's location. That is all that is to be done to install the customized text document handler!

Simple test

Create a new text file name test.aaa and place it under your web virtual directory. When you type the link http://localhost/ASP.NET/test.aaa, here my virtual directory is ASP.NET, you should see the text file display on your browser (remember to start your IIS service first!). To test what will happen when the file does not exist, try http://localhost/ASP.NET/test1.aaa and an error message will display from the handler program and you are sure your HTTP handler in fact is taking the control to give response for the request. Try to display a very large text document, the asynchronous method will display part of the file on browser as soon as it read ahead some data. This will provide better responsive user experience!

Conclusion

With new .NET HTTP handler customization capability, we can easily add functionality like text document handler without a hitch! Text handler is just my throw a stone simple example, you can create much more sophisticated HTTP handler to handle much different type of files, and limitation is your imagination!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here