Click here to Skip to main content
15,390,695 members
Articles / Web Development / ASP.NET
Posted 15 Sep 2002


38 bookmarked

Customized Text Document .NET HTTP Handler

Rate me:
Please Sign up or sign in to vote.
4.50/5 (3 votes)
15 Sep 20022 min read
Customized text document .NET HTTP handler to process text file not with standard extensions, like .aaa, .xxx.


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 ; = 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(, 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( ;
          fs.BeginRead(, 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:

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

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

Step 3

Image 1

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 and place it under your web virtual directory. When you type the link http://localhost/ASP.NET/, 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/ 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!


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!


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


About the Author

Matthew So (Hong Kong)
Founder Software Force
Hong Kong Hong Kong
I am always interested in finding innovative ways for building better applications and founded a technology company since 2003. Welcome to exchange any idea with you and if I am not too busy before deadline of projects, I will reply your emails. Also, if you willing to pay for consulting works and customized software development, you can leave me message.

Comments and Discussions

GeneralXSS vulnerable Pin
Whatabohr2-Jul-03 11:09
MemberWhatabohr2-Jul-03 11:09 
GeneralRe: XSS vulnerable Pin
Matthias Gerloff25-Aug-03 10:42
MemberMatthias Gerloff25-Aug-03 10:42 
GeneralRe: XSS vulnerable Pin
Whatabohr25-Aug-03 10:56
MemberWhatabohr25-Aug-03 10:56 
GeneralRe: XSS vulnerable Pin
Matthias Gerloff26-Aug-03 8:01
MemberMatthias Gerloff26-Aug-03 8:01 
GeneralMIME Type Pin
Ryan LaNeve16-Sep-02 7:14
MemberRyan LaNeve16-Sep-02 7:14 
GeneralRe: MIME Type Pin
Matthew So (Hong Kong)16-Sep-02 13:46
MemberMatthew So (Hong Kong)16-Sep-02 13:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.