Wednesday, December 17, 2008

Difference Between Aspx and ashx files

Hi,
Here is the details about ashx file When some one new to this topic

Ashx File is nothing but just like an aspx page.They're equivalent to custom handlers written in C Sharp or Visual Basic.NET in that they contain classes that fully implement IHttpHandler. They're convenient in the same way ASPX files are convenient. You simply surf to them and they're compiled automatically.

When WebForms(aspx)to be used
Simple Html Pages
Asp.net Custom Controls
Simple Dyanamic Pages

When Handlers(ashx) to be used
Binary files
Dynamic Image Views
Performance critical web pages
xml files
Minimal Web Pages

Add the New item Generic handler in the Asp.Net Website

Here is the Example to use HttpHandler

It defines two parts of the IHttpHandler interface. The important part is ProcessRequest(), which will be invoked whenever the Handler.ashx file is requested or pointed to.

1.Map the Handler:
you will probably want the new handler to take over an old URL in your site. To do this, use urlMappings.

2.Add Image In to ur Project
Juz add the image in to the project , to use the image in the handler

3. Modify your Handler.ashx
Here You must modify the process request.Juz modify the code as below
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
// Comment out these lines first:
// context.Response.ContentType = "text/plain";
// context.Response.Write("Hello World");

context.Response.ContentType = "image/png";
context.Response.WriteFile("~/Flower1.png");
}

public bool IsReusable {
get {
return false;
}
}
}

4.Now compile and run the default.aspx
Above Specified is simple application
Here is the other sample to handle the handler with the query string
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {

HttpResponse r = context.Response;
r.ContentType = "image/png";
//
// Write the requested image
//
string file = context.Request.QueryString["file"];
if (file == "logo")
{
r.WriteFile("Logo1.png");
}
else
{
r.WriteFile("Flower1.png");
}
}

public bool IsReusable {
get {
return false;
}
}
}
It juz checks the querystring and display the result as specified

Handlers vs. web pages. ASP.NET web forms inherit from the Page class. This provides them with many events and a very detailed initialization and event model. You don't need that for dynamic images, XML, or binary files.

Why is it faster? It is faster because it does a lot less. As you can imagine firing 10+ events each time a request is handled is a fair amount more expensive than only firing one event.


No comments: