.ashx 文件
(1)、使用举例
.ashx文件是主要用来写web handler的。使用.ashx 可以让你专注于编程而不用管相关的web技术。我们熟知的.aspx是要做html控件树解析的,.aspx包含的所有html实际上是一个类,所有的html都是类里面的成员,这个过程在.ashx是不需要的。ashx必须包含IsReusable属性(这个属性代表是否可复用,通常为true),而如果要在ashx文件用使用Session必须实现IRequiresSessionState接口.
一个简单的实现修改登录用户密码的示例:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Web.SessionState; namespace Test { public class HandlerTest : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ClearContent(); context.Response.ContentType = "text/plain"; context.Response.Cache.SetCacheability(HttpCacheability.NoCache); //无缓存 string action = context.Request.Params["action"]; //外部请求 if (action == "modifyPwd") //用户改密码 { string oldPwd = context.Request.Params["pwd"]; //在ashx文件用使用Session必须实现IRequiresSessionState接口 //Session["LogedUser"]是登录用户的会话,用户名和密码都是test if (oldPwd.ToUpper() != ((context.Session["LogedUser"]) as Customer).Password.ToUpper()) //用户输入的旧密码和当前登录用户的不相同 { context.Response.Write("旧密码输入错误!"); } else { context.Response.Write("旧密码输入正确!"); } } context.Response.End(); } public bool IsReusable { get { return true; } } } }
客户端的调用(js和页面部分):
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ASHXTest.aspx.cs" Inherits="ASHXTest" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>mytest</title> <script type="text/javascript"> function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } } function createXMLHTTP() { var xmlHttp = false; var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; for (var i = 0; i < arrSignatures.length; i++) { try { xmlHttp = new ActiveXObject(arrSignatures[i]); return xmlHttp; } catch (oError) { xmlHttp = false; //ignore } } // throw new Error("MSXML is not installed on your system."); if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } return xmlHttp; } var xmlReq = createXMLHTTP(); // 发送ajax处理请求(这里简单验证旧密码的有效性) function validateOldPwd(oTxt) { var url = "/HandlerTest.ashx?action=modifyPwd&pwd=" + escape(oTxt.value); //.ashx文件 xmlReq.open("get", url, true); xmlReq.setRequestHeader("If-Modified-Since", "0"); xmlReq.onreadystatechange = callBack; xmlReq.send(url); // 发送文本 } function callBack() { if (xmlReq.readyState == 4) { if (xmlReq.status == 200) { alert(xmlReq.responseText); // 接收文本 } else if (xmlReq.status == 404) { alert("Requested URL is not found."); } else if (xmlReq.status == 403) { alert("Access denied."); } else alert("status is " + xmlReq.status); } } </script> </head> <body> <form id="form1" runat="server"> <div> <input id="txtOldPwd" type="text" onblur="validateOldPwd(this)" /> </div> </form> </body> </html>
分析:
a、以前我们通常都是通过一个简单的aspx文件实现的功能,其实通过ashx也可以。
笔者曾经写过的一篇ajax:数据传输方式简介 ,通过对比,我们发现aspx要将前后台显示和处理逻辑分开,所以就弄成了两个文件,其实,在最终编译的时候,aspx和cs还是会编译到同一个类中去.这中间就要设计html的一些逻辑处理;而ashx不同,它只是简单的对web http请求的直接返回你想要返回的结果.比aspx少处理了html的过程(但是ashx也可以处理html的一些逻辑,只是通常都不这么用)。理论上ashx比aspx要快。
b、还是在相同的旧文里,我们知道数据传输的几种方式,其实ashx都可以实现(修改ashx文件里context.Response.ContentType 即可),这里不再赘述了。
(2)、ashx特别适合于生成动态图片,生成动态文本(纯文本,json,xml,javascript等即可)等。
(3)、.ashx文件有个缺点:它处理控件的回发事件非常麻烦。处理数据的回发,通常都需要一些.aspx页的功能,只有自己手动处理这些功能(还不如直接建一个aspx文件来处理)。所以,一般使用.ashx输出一些不需要回发处理的项目即可。