httpHandlers和httpModules介面介紹 (4)

來源:互聯網
上載者:User

Web.Config設定檔

<httpHandlers><add verb="*" path="*" type="ClassLibrary831.TestHandler,ClassLibrary831"></add></httpHandlers>

Verb屬性:指定了處理常式支援的HTTP動作。*-支援所有的HTTP動作;“GET”-支援Get操作;“POST”-支援Post操作;“GET, POST”-支援兩種操作。

Path屬性:指定了需要調用處理常式的路徑和檔案名稱(可以包含萬用字元)。“*”、“*.aspx”、“showImage.aspx”、“test1.aspx,test2.aspx”

Type屬性:用名字空間、類名稱和程式集名稱的組合形式指定處理常式或處理常式工廠的實際類型。ASP.NET運行時首先搜尋bin目錄中的DLL,接著在GAC中搜尋。

這樣程式啟動並執行效果是該網站的任何一個頁面都會顯示worm.jpg圖片。如何只讓一個頁面(default21.aspx)執行HttpHandler中的ProcessRequest方法呢?最簡單的辦法是在Web.Config檔案中把path配置資訊設為default21.aspx。

根據這個例子大家可以考慮一下如何編寫“驗證碼”了。

IHttpHandler工廠IHttpHandlerFactory的作用是對IHttpHandler進行管理。工廠的作用請見http://hi.baidu.com/grayworm/blog/item/4a832160f8c9de46eaf8f8c1.html"IHttpHandlerFactory介面的聲明:public interface IHttpHandlerFactory{IHttpHandler GetHandler (HttpContext context,string requestType,string url,string pathTranslated);void ReleaseHandler (IHttpHandler handler);}

GetHandler返回實現IHttpHandler介面的類的執行個體,ReleaseHandler使工廠可以重用現有的處理常式執行個體。

樣本:兩個用IHttpHandlerFactory來實現對不同HttpHandler的調用。

有兩個HttpHandler:將圖片顯示在頁面上的HttpHandler和產生驗證碼的Handler

//將圖片顯示在頁面上的Handler

class TestHandler : IHttpHandler{public void ProcessRequest(HttpContext context){FileStream fs = new FileStream(context.Server.MapPath("worm.jpg"), FileMode.Open);byte[] b = new byte[fs.Length];fs.Read(b, 0, (int)fs.Length);fs.Close();context.Response.OutputStream.Write(b, 0, b.Length);}public bool IsReusable{get{return true;}}}//產生驗證碼的Handler class CodeHandler:IHttpHandler{public bool IsReusable{get{return true;}}public void ProcessRequest(HttpContext context){Image b = new Bitmap(50,20);Graphics g = Graphics.FromImage(b);SolidBrush sb = new SolidBrush(Color.White);Font f = new Font("宋體", 12);string str = "";Random r = new Random();for (int i = 0; i < 4; i++){str += r.Next(10);}g.DrawString(str,f,sb,0,0);b.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.