Asp.net中的HttpModule和HttpHandler的簡單用法

來源:互聯網
上載者:User

標籤:

在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的簡單用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.