asp.net中的HttpHandler解决方案 - OPS.ExecuteHandler组件
请看介绍这个解决方案的两篇文章
更灵活,更易维护的WebHandler之通用webHandler编码方案(1)
更灵活,更易维护的WebHandler之通用webHandler编码方案(2)
此次在原有基础上进行大规模的改进和升级:
添加 IWebExecute 接口。用于对执行类和类的方法时候进行更多控制!
内置:PostAttribute和GetAttribute 均实现了IWebExecute接口!
使用方法如下:
一:引用OPS.Lib.dll到项目中
二:向ExecuteHandler注册
namespace OPS.HandlerDemo
{
using OPS.Web; //引用命名空间
public class WebHandler:ExecuteHandler
{
static WebHandler()
{
_type=typeof(Login);
}
}
}
三:注册Handler载体 -- 一般程序处理程序(.ashx后缀的文件)
添加ops.ashx文件,代码如下:
<%@ WebHandler Class="OPS.HandlerDemo.WebHandler" %>
我们使用ops.ashx来执行类和调用类的方法
ops.ashx参数说明:
ops.ashx?task=类名,方法名,参数(多个参数用","隔开)
例:ops.ashx?task=login,enter,ops,ops
(执行login类的enter方法,两个ops为enter方法的两个参数)
四:创建可被ExecuteHandler执行的类
如果需要被ExecuteHandler执行,则需要为类型添加 WebExecuteable 特性
namespace OPS.HandlerDemo.Login
{
[WebExecuteable] //必须添加此特性类型的方法才能被调用
public class Login
{
public string Enter(string username, string password)
{
return "成功";
}
}
}
运行ops.ashx?task=login,enter,ops,ops,你将会看见成功字样!

五:使用内置的Post和Get特性
1.为方法添加Post特性将可以阻止用户发送GET请求,如:
namespace OPS.HandlerDemo.Login
{
[WebExecuteable] //必须添加此特性类型的方法才能被调用
public class Login
{
[Post]
public string Enter(string username, string password)
{
return "成功";
}
}
}
在浏览器中直接输入地址将出现结果如图:

2.Get特性,跟Post同理
3.阻止短时间内的多次反复请求

只需要为Get或Post特性的AllowRefreshMillliSecond属性赋值就可以简单实现!如:
//1秒种之内只允许请求一次,否则提示服务不可用
[Get(AllowRefreshMillliSecond=1000)]
public string Enter(string username, string password)
{
return "成功";
}
六:为ExecuteHandler创建自定义特性
我们将通过实例创建一个NotLoginAttribute让已经登陆的用户不能再次登陆
using OPS.Web;
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,AllowMultiple=false,Inherited=false)]
public class NotLoginAttribute:Attribute,IWebExecute
{
#region IWebExecute 成员
//实现IWebExecute的方法
public void PreExecuting()
{
HttpContext.Current.Response.Write("已经登陆");
HttpContext.Current.Response.End();
}
#endregion
}
并在Login类的Enter方法上应用此特性
namespace OPS.HandlerDemo.Login
{
using OPS.Web;
[WebExecuteable] //必须添加此特性类型的方法才能被调用
public class Login
{
[Get]
[NotLogin]
public string Enter(string username, string password)
{
return "成功";
}
}
}
再次打开浏览器请求ops.ashx?task=login,enter,ops,ops
结果如下:

该组件在创建Ajax应用时候能简化很多工作,使用该组件可以称的上是在写类型,而不是写页面
点击这里下载ExecuteHandler的代码文件:
本地下载地址:https://files.cnblogs.com/newmin/ops.lib.rar
官方主页下载:http://www.ops.cc/lib/
浙公网安备 33010602011771号