Click here to Skip to main content
15,868,016 members
Articles / Web Development / ASP.NET
Article

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 90.1K   543   38   6
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:

C#
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:

XML
<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

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 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


Written By
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
Whatabohr2-Jul-03 11:09 
GeneralRe: XSS vulnerable Pin
Matthias Gerloff25-Aug-03 10:42
Matthias Gerloff25-Aug-03 10:42 
GeneralRe: XSS vulnerable Pin
Whatabohr25-Aug-03 10:56
Whatabohr25-Aug-03 10:56 
GeneralRe: XSS vulnerable Pin
Matthias Gerloff26-Aug-03 8:01
Matthias Gerloff26-Aug-03 8:01 
GeneralMIME Type Pin
Ryan LaNeve16-Sep-02 7:14
Ryan LaNeve16-Sep-02 7:14 
GeneralRe: MIME Type Pin
Matthew So (Hong Kong)16-Sep-02 13:46
Matthew 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.