做asp.net开发的对.aspx,.ascx和.ashx都不会陌生。关于它们,网上有很多文章介绍。“纸上得来终觉浅,绝知此事要躬行”,下面自己总结一下做个笔记。
1、.aspx
Web窗体设计页面。Web窗体页由两部分组成:视觉元素(html、服务器控件和静态文本)和该页的编程逻辑(VS中的设计视图和代码视图可分别看到它们对应得文件)。VS将这两个组成部分分别存储在一个单独的文件中。视觉元素在.aspx 文件中创建。
2、.ascx
asp.net的用户控件,是作为一种封装了特定功能和行为(这两者要被用在Web应用程序的各种页面上)的Web页面被开发的。一个用户控件包含了html、代码和其他Web或者用户控件的组合,并在Web服务器上以自己的文件格式保存,其扩展名是*.ascx。asp.net里的缺省配置并不允许Web客户端通过url来访问这些文件,但是这个网站的其他页面可以集成这些文件里所包含的功能。
3、.ashx
前面两个都太熟悉了,这个才是要讲的重点。
(1)、使用举例
.ashx文件是主要用来写web handler的。使用.ashx 可以让你专注于编程而不用管相关的web技术。我们熟知的.aspx是要做html控件树解析的,.aspx包含的所有html实际上是一个类,所有的html都是类里面的成员,这个过程在.ashx是不需要的。ashx必须包含IsReusable属性(这个属性代表是否可复用,通常为true),而如果要在ashx文件用使用Session必须实现IRequiresSessionState接口.
一个简单的实现修改登录用户密码的示例:
CodeusingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Security;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Web.UI.WebControls.WebParts;usingSystem.Web.UI.HtmlControls;usingSystem.Web.SessionState;namespaceTest
{publicclassHandlerTest : IHttpHandler, IRequiresSessionState
{publicvoidProcessRequest(HttpContext context)
{
context.Response.ClearContent();
context.Response.ContentType="text/plain";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);//无缓存stringaction=context.Request.Params["action"];//外部请求if(action=="modifyPwd")//用户改密码{stringoldPwd=context.Request.Params["pwd"];//在ashx文件用使用Session必须实现IRequiresSessionState接口//Session["LogedUser"]是登录用户的会话,用户名和密码都是testif(oldPwd.ToUpper()!=((context.Session["LogedUser"])asCustomer).Password.ToUpper())//用户输入的旧密码和当前登录用户的不相同{
context.Response.Write("旧密码输入错误!");
}else{
context.Response.Write("旧密码输入正确!");
}
}
context.Response.End();
}publicboolIsReusable
{get{returntrue;
}
}
}
}
客户端的调用(js和页面部分):
Codehtml PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">mytestfunction$(s) {if(document.getElementById) {returneval('document.getElementById("'+s+'")'); }else{returneval('document.all.'+s); } }functioncreateXMLHTTP() {varxmlHttp=false;vararrSignatures=["MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"];for(vari=0; i
xmlHttp=newActiveXObject(arrSignatures[i]);returnxmlHttp;
}catch(oError) {
xmlHttp=false;//ignore}
}//throw new Error("MSXML is not installed on your system.");if(!xmlHttp&&typeofXMLHttpRequest!='undefined') {
xmlHttp=newXMLHttpRequest();
}returnxmlHttp;
}varxmlReq=createXMLHTTP();//发送ajax处理请求(这里简单验证旧密码的有效性)functionvalidateOldPwd(oTxt) {varurl="/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);//发送文本}functioncallBack() {if(xmlReq.readyState==4) {if(xmlReq.status==200) {
alert(xmlReq.responseText);//接收文本}elseif(xmlReq.status==404) {
alert("Requested URL is not found.");
}elseif(xmlReq.status==403) {
alert("Access denied.");
}elsealert("status is"+xmlReq.status);
}
}