随笔 - 394  文章 - 0  评论 - 946  阅读 - 143万 

在Asp.net中,HttpModule和HttpHandler均可以截取IIS消息进行处理,这使得我们制作人员能够非常方便的进行诸如图片水印添加,图片盗链检查等功能。

下面先就HttpModule的使用方法进行简单说明:

复制代码
using System;
using System.Web;

namespace MyWebApp
{
public class MyHttpModule:IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest
+=new EventHandler(application_BeginRequest);
}

public void application_BeginRequest(object sender, EventArgs e)
{
HttpContext context
= (sender as HttpApplication).Context;
context.Response.Write(
"这一部分是由HttpModule添加!<br><script>alert('测试脚本标签')</script>");
}

#region IHttpModule 成员

void IHttpModule.Dispose()
{
throw new NotImplementedException();
}

#endregion
}
}
复制代码

需要说明的是,使用HttpModule的时候需要继承自IHttpModule接口,然后需要实现Dispose成员。需要注意一点的是,这些操作还得在web.config中进行配置,才能够正常使用:

      <!--下面这里是添加的自定义的HTTPModule-->
<add name="MyHttpModule" type="MyWebApp.MyHttpModule"/>

而对于HttpHandler,则需要继承自IHttpHandler接口,并且也需要在web.config中进行注册:

复制代码
using System.Web;
using System.Web.Services;

namespace MyWebApp
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo
= WsiProfiles.BasicProfile1_1)]
public class MyHttpHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType
= "text/plain";
context.Response.Write(
"这一部分是由HttpHandler添加!");
}

public bool IsReusable
{
get
{
return false;
}
}
}
}
复制代码

在web.config中的注册如下:

      <!--下面是添加的自定义HTTPHandler-->  
<add verb="*" path="*.aspx" type="MyWebApp.MyHttpHandler"/>

希望对你有用。

posted on   程序诗人  阅读(963)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示