Click here to Skip to main content
Click here to Skip to main content
Go to top

Customized Text Document .NET HTTP Handler

, 15 Sep 2002
Rate this:
Please Sign up or sign in to vote.
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

Share

About the Author

matthew_from_hk
Founder
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 PinmemberWhatabohr2-Jul-03 11:09 
GeneralRe: XSS vulnerable PinmemberMatthias Gerloff25-Aug-03 10:42 
GeneralRe: XSS vulnerable PinmemberWhatabohr25-Aug-03 10:56 
GeneralRe: XSS vulnerable PinmemberMatthias Gerloff26-Aug-03 8:01 
GeneralMIME Type PinmemberRyan LaNeve16-Sep-02 7:14 
Adding a MIME entry in IIS for the desired extension (".aaa" in this example) set to a type of "Text/plain" yields the same result and takes less than a minute.
 
While I appreciate the possibilities of HttpHandlers (having used them extensively myself), and this article does outline the steps necessary to setup a custom handler (entry in Web.config, addition of ISAPI extension mapped to aspnet_isapi.dll, etc...), the useage here is too simplistic. This is a good example of when a programmer needs to refrain from using technology for the sake of technology.
 
Ryan LaNeve
www.laneve.com
GeneralRe: MIME Type PinmemberYuen Chiu So16-Sep-02 13:46 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140905.1 | Last Updated 16 Sep 2002
Article Copyright 2002 by matthew_from_hk
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid