很多時候,我們新建一個xxx.aspx頁和xxx.aspx.cs文件,不過是為了實現一個很簡單的功能,如:輸出xmldom,注銷并跳轉,并沒有什么html的輸出,很是麻煩,需要新建一個頁,刪除多余的html,并在page_load里面寫處理代碼。而使用httphandler就不需要這么麻煩了。
可以用任何符合公共語言規范 (cls) 的語言編寫自定義 http 處理程序來處理特定的、預定義類型的 http 請求。響應這些特定請求的是在 httphandler 類中定義的可執行代碼,而不是常規的 asp 或 asp.net web 頁。http 處理程序向您提供一種方法,使您可以與 iis web 服務器的低級別的請求和響應服務交互,同時提供極其類似于 isapi 擴展但編程模型較為簡單的功能。
例如我現在需要實現一個注銷并跳轉的logout.aspx頁面,下面的示例主要實現了響應客戶端對名為 logout.aspx 的頁的請求,實現注銷并跳轉。對 logout.aspx 的所有請求均由包含在程序集 webuc.dll 中的命名空間 webuc.httphandler 中的 logouthttphandler 提供服務。
修改web.config,在<system.web></system.web>中增加如下腳本:
<httphandlers>
 <add verb="get" path="logout.aspx" type="webuc.httphandler.logouthttphandler, webuc" />
</httphandlers>
其中webuc.httphandler.logouthttphandler是我要實現logout.aspx功能的類,webuc是我web項目的dll。(具體介紹可以參閱msdn)
下面是logouthttphandler的代碼,繼承借口,重寫方法和屬性。
using system;
using system.web;
using system.web.caching;
using system.web.security;
namespace webuc.httphandler 
{
 public class logouthttphandler : ihttphandler 
 {
  /// <summary>
  /// 通過實現 ihttphandler 接口的自定義 httphandler 啟用 http web 請求的處理。
  /// </summary>
  /// <param name="context">httpcontext 對象,它提供對用于為 http 請求提供服務的內部服務器對象(如 request、response、session 和 server)的引用。 </param>
  public void processrequest (httpcontext context) 
  {
   formsauthentication.signout();
   context.response.redirect("login.aspx",true);
  }
  /// <summary>
  /// 獲取一個值,該值指示其他請求是否可以使用 ihttphandler 實例。
  /// </summary>
  public bool isreusable 
  {
   get 
   {
    return false;
   }
  }
 }
 }
}
編譯后,我就可以直接使用http://***/logout.aspx 來實現注銷了,
而實際上,我的web目錄下并沒有logout.aspx這個文件,同樣,
這個技巧可以用在很多方面,例如防止盜鏈,下載統計等。
新聞熱點
疑難解答
圖片精選