ASHX File

If you are familiar with ASP .Net you will know files with extenstion .aspx , .asmx, .asax, .config and .ascx… Because these extenstions you always use on your every working day. Yesterday I got an email from may Boss to provide a page with extension .ashx. On the first place , I thought it just miss typo. But it made me such curious, was my boss missed typo the word. To fulfill my curiosity, the best way is to ask uncle google to answer the question :).. Ya, .ashx is part of ASP .Net extensions. Usually .ashx is used as a web handler. A web handler file works just like an aspx file except you are one step back away from the messy browser level where HTML and C# mix. One reason you would write an .ashx file instead of an .aspx file is that your output is not going to a browser but to an xml-consuming client of some kind. Working with .ashx keeps you away from all the browser technology you don’t need in this case. Notice that you have to include the IsReusable property.

<%@ webhandler language=”C#” class=”SuccessHandler” %>

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

public class SuccessHandler : IHttpHandler
{
public bool IsReusable
{ get { return true; } }

public void ProcessRequest(HttpContext ctx)
{
// create a write stream
FileStream writeStream = new FileStream(string.Format(“/success/{0}.txt”, Guid.NewGuid().ToString()), FileMode.Create, FileAccess.Write);
ReadWriteStream(ctx.Request.InputStream, writeStream);
}

// readStream is the stream you need to read
// writeStream is the stream you want to write to
private void ReadWriteStream(System.IO.Stream readStream, System.IO.Stream writeStream)
{
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s