Creating an ASHX handler in ASP.NET
Today a typical web application is not only about serving HTML to browsers, but also serving XML and other types of content. Say you are creating a RSS feed for your site, for example. RSS should be presented as XML and I will cover that specific case in another article (will be available in related articles when posted) but this particular article will just show you the basics of putting an ASHX page handler up.
Problem
We want to create a page on our site returning an XML file to the visitor.
Possible solution
There are lots of suggestions creating a regular ASPX page (say rss.aspx) and in Page_Load use Response.Write to return the XML. Example:
public class RSS : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
Response.ContentType = "text/xml";
Response.ContentEncoding = Encoding.UTF8;
string sXml = BuildXMLString(); //not showing this function,
//but it creates the XML string
Response.Write( sXml );
Response.End();
}
}
This will indeed work, and since it is a regular page you have great options to improve performance just with some page declarations at the top of the rss.aspx file:
<!--OutputCache Duration="600" VaryByParam="None"-->
Now what's wrong with it? Well, basically nothing, but it is a fact that our page class (RSS) inherits from System.Web.UI.Page and that page handler is indented for serving aspx pages (i.e WebForms) and includes a lot of overhead not needed for just serving a simple XML file.
Alternate solution
There are other solutions. You can create your own page handlers, and you can even map your own file extentions to your handlers, for example you could invent your own file extention called .myspecialrss. Now you can (with some configurations settings in IIS/web.config) map all requests to whatever.myspecialrss to your own special file handler. However, needing to do some configurations are never fun to do - if even possible in a shared hosting scenario, therefore Microsoft has kindly given us a special filetype .ASHX which maps to the ASP.NET engine.
Now what we are going to is is create a file - rss.ashx - which when called returns the same XML as in the example above. If you have forgotten why - the ashx handler doesn't give us all that overhead as a .aspx request does.
So, start off by creating
rss.ashx
<!--WebHandler Language="C#" Class="KBMentor2.RSSHandler"-->
Yes, thats correct, just one single line. It says the class for our Webhandler is called KBMentor2.RSSHandler, so we will now create that class. To put it simple - what happens is that when the request for rss.ashx comes to the ASP.NET engine it reads the rss.ashx file, sees that the class is KBMentor2.RSSHandler and therefore instantiates an object of that class.
Now lets have a look at the handler class:
RSSHandler.cs
namespace KBMentor2
{
using System;
using System.IO;
using System.Web;
public class RSSHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/xml";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
string sXml = BuildXMLString(); //not showing this function,
//but it creates the XML string
context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Write( sXml );
}
public bool IsReusable
{
get { return true; }
}
}
}
And there you have it. Looks pretty much like the first code we created, doesn't it? As for caching, you can solve it by accessing the Cache object from your code, see the context.Response.Cache calls.
from:http://www.aspcode.net/Creating-an-ASHX-handler-in-ASPNET.aspx
.ashx 文件用于写web handler的。其实就是带HTML和C#的混合文件。当然你完全可以用.aspx 的文件后缀。使用
.ashx 可以让你专注于编程而不用管相关的WEB技术。
.ashx必须包含IsReusable. 如下例所示
<% @ webhandler language="C#" class="AverageHandler" %>
using System;
using System.Web;
public class AverageHandler : IHttpHandler
{
public bool IsReusable
{ get { return true; } }
public void ProcessRequest(HttpContext ctx)
{
ctx.Response.Write("hello");
}
}
.ashx比.aspx的好处在与不用多一个html
注意了VS2005中Web应用程序项目模板里的Generic Handler 项,发现它是一个.ashx文件,实际上它是一个HttpHandler。后来查了一下.Net SDK文档,发现Asp.Net1.1也支持.ashx,但是没有给出详细内容。
我们都知道,HttpHandler是一个彻底自定义Http请求的方法,它通过web.config来定义Asp.Net运行时来过滤出要自定义的Http请求,发送到定义在web.config的指定类中。
利用.ashx文件是一个更好的方法,这个文件类似于.aspx文件,可以通过它来调用HttpHandler类,从而免去了普通.aspx页面的控件解析以及页面处理的过程。这个文件特别适合于生成动态图片,生成动态文本等内容。
建立方法如下:
首先打开一个Web项目,然后在任意目录下使用VS2003解决方案资源管理器的“添加”-->“添加新项”,在对话框中选择“文本文件”,然后在文件名处输入“TextBuilder.ashx”。
然后在同目录下,使用解决方案资源管理器,使用“添加”-->“添加类”,在类文件名处输入“TextBuilder.ashx.cs”。可以看出,它的文件命名规律与.aspx文件相同。
然后在.cs文件处输入以下代码(名称空间略):
using
System.Web
public
sealed
class
TextBuilder : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ClearContent();
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
context.Response.End();
}
public bool IsReusable
{
get { return true; }
}
}
然后在“TextBuilder.ashx”文件的第一行处输入上面这个类的调用代码:
<%
@ WebHandler language="C#" Class="MyNamespace.TextBuilder" codebehind="TextBuilder.ashx.cs"
%>
上面的代码需要注意的是:必须在Class项中输入类的完整名称,即包括名称空间及类名称。
最后保存并编译项目。
使用IE测试,输入这个.ashx的地址即可。
大家可以看出Response类有个OutputStream方法,可以向客户端输出二进制数据流,所以在我的项目中,使用这个方法,在一个.ashx中 使用DundasChart控件就可以生成非常好的统计图,用它发送二进制数据,方便快捷,而且不需在web.config内输入任何配置代码。
.ashx文件有个缺点,他处理控件的回发事件非常麻烦,比如说如果用它来生成DataGrid的列表也不是不行,但是处理数据的回发,需要一些.aspx页的功能,只有自己手动处理这些功能。所以,一般使用.ashx,用来输出一些不需要回发处理的项目即可。
from :http://www.cnblogs.com/lin614/archive/2008/01/18/1044734.html