asp.net中的HttpHandler解决方案 - OPS.ExecuteHandler组件
请看介绍这个解决方案的两篇文章
更灵活,更易维护的WebHandler之通用webHandler编码方案(1)
更灵活,更易维护的WebHandler之通用webHandler编码方案(2)
此次在原有基础上进行大规模的改进和升级:
添加 IWebExecute 接口。用于对执行类和类的方法时候进行更多控制!
内置:PostAttribute和GetAttribute 均实现了IWebExecute接口!
使用方法如下:
一:引用OPS.Lib.dll到项目中
二:向ExecuteHandler注册
1 2 3 4 5 6 7 8 9 10 11 12 | namespace OPS.HandlerDemo { using OPS.Web; //引用命名空间 public class WebHandler:ExecuteHandler { static WebHandler() { _type= typeof (Login); } } } |
三:注册Handler载体 -- 一般程序处理程序(.ashx后缀的文件)
添加ops.ashx文件,代码如下:
1 | <%@ 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 特性
1 2 3 4 5 6 7 8 9 10 11 | 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请求,如:
1 2 3 4 5 6 7 8 9 10 11 12 | 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 2 3 4 5 6 | //1秒种之内只允许请求一次,否则提示服务不可用 [Get(AllowRefreshMillliSecond=1000)] public string Enter( string username, string password) { return "成功" ; } |
六:为ExecuteHandler创建自定义特性
我们将通过实例创建一个NotLoginAttribute让已经登陆的用户不能再次登陆
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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方法上应用此特性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述