|
ashx文件没有页面元素,这点上区别于aspx页面,所以在效率上要比aspx页面高,通常用于ajax提交处理程序,实际项目中,用户的每个请求需要判断用户是否登录,可以是Cookie, Session,每个请求页面中去写判断用户是否登录的方法过于麻烦,所以可以通过一个基类实现所有请求方法前的用户登录状态判断。应用基类的好处可以将一些基本验证,公用方法,函数统一处理。
BaseHandle.ashx - /// <summary>
- /// 基类
- /// ashx中如果要使用Session需要继承 IRequiresSessionState 接口
- /// </summary>
- public class BaseHandler : IHttpHandler, IRequiresSessionState
- {
- /// <summary>
- /// 请求处理
- /// </summary>
- /// <param name="context"></param>
- public void ProcessRequest(HttpContext context)
- {
- // 逻辑验证, 如: 用户登录验证
- // ...
- // ...
- // ...
- if (1 == 0)
- {
- context.Response.ContentType = "text/plain";
- context.Response.Write("error");
- return;
- }
-
- context.Response.ContentType = "text/plain";
- context.Response.Write("BaseHandler");
-
- AjaxRequest(context);
- }
-
- /// <summary>
- /// ajax请求, 继承页面进行请求调用
- /// </summary>
- /// <param name="context"></param>
- public virtual void AjaxRequest(HttpContext context) { }
-
- public bool IsReusable
- {
- get
- {
- return false;
- }
- }
- }
复制代码继承页面,Test.ashx - public class Test : BaseHandler
- {
- public override void AjaxRequest(HttpContext context)
- {
- context.Response.ContentType = "text/plain";
- context.Response.Write("Test");
-
- // 业务逻辑
- // ...
- // ...
- // ...
- }
- }
复制代码
|