標籤:
在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"/>
希望對你有用。
Asp.net中的HttpModule和HttpHandler的簡單用法