學(xué)習(xí)整理了一下
(一). HttpHandlers能夠處理對(duì)某種特定文件類(lèi)型的請(qǐng)求.
例如, 在machine.config 文件中默認(rèn)已經(jīng)有大部分的系統(tǒng)處理Handlers:
<httpHandlers>
<add verb=”*” path=”*.aspx” type=”System..Web.UI.PageHandlerFactory” />
<add verb=”*” path=”*.ascx” type=”System..Web.HttpForbiddenHandler” />
<add verb=”*” path=”*.cs” type=” System..Web.HttpForbiddenHandler” />
<add verb=”*” path=”*.skin” type=” System..Web.HttpForbiddenHandler” />
<add verb=”*” path=”*.sitemap” type=” System..Web.HttpForbiddenHandler” />
…….
</httpHandlers>
創(chuàng)建一個(gè)HttpHandler也非常簡(jiǎn)單,下面將創(chuàng)建一個(gè)自定義的HttpHandler,
功能為驗(yàn)證訪問(wèn): *.jpeg/jpg 圖像文件權(quán)限. 通過(guò)這個(gè)示例演示其用法.
(二).代碼如下
1. 處理程序HttpHandler文件 JpgHandler.cs 代碼
1 using System; 2 using System.Data; 3 using System.Configuration; 4 using System.Web; 5 using System.Web.Security; 6 using System.Web.UI; 7 using System.Web.UI.WebControls; 8 using System.Web.UI.WebControls.WebParts; 9 using System.Web.UI.HtmlControls; 10 11 /// <summary> 12 /// 只有 admin 權(quán)限用戶才能直接查看 JPG和JPEG的圖片 13 /// </summary> 14 public class JpgHandler : IHttpHandler 15 { 16 public JpgHandler() 17 { 18 } 19 public void ProcessRequest(HttpContext hc) 20 { 21 string strFileName = hc.Server.MapPath( hc.Request.FilePath ); 22 if (hc.User.IsInRole("admin")) //當(dāng)前用戶是否為 admin 權(quán)限 23 { 24 hc.Response.ContentType = "image/JPEG"; 25 hc.Response.WriteFile(strFileName); 26 } 27 else 28 { 29 hc.Response.ContentType = "image/JPEG"; 30 hc.Response.Write("No Right"); 31 } 32 } 33 public bool IsReusable 34 { 35 get 36 { 37 return true; 38 } 39 } 40 } 41 2.前臺(tái)頁(yè)面 *.aspx 代碼
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 2 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 <html xmlns="http://www./1999/xhtml" > 6 <head runat="server"> 7 <title>HttpHandler validate users right</title> 8 </head> 9 <body> 10 <form id="form1" runat="server"> 11 <div> 12 <asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="a.jpeg" ToolTip="Click me!" OnClick="LinkButton1_Click" Width="149px">A.jpeg</asp:LinkButton> 13 14 </div> 15 </form> 16 </body> 17 </html> 18 3.在Web.Config文件中注冊(cè)自己的處理程序類(lèi)配置 1 <system.web> 2 <httpHandlers> 3 <add verb="*" path="*.jpg,*.jpeg" type="JpgHandler" /> 4 </httpHandlers> 5 </system.web> 6 在這里我是將處理程序類(lèi) JpgHandler.cs 放到 App_Code文件夾下面,如果此類(lèi)不是放在此類(lèi)下面,而是以程序集*.dll格式的,則應(yīng)該將此程序集放到bin目錄下面,并且這樣配置: 1 <system.web> 2 <httpHandlers> 3 <add verb="*" path="*.jpg,*.jpeg" type="JpgHandler,YourDll" /> 4 </httpHandlers> 5 </system.web> 6 (三). 示例代碼下載 |
|
來(lái)自: 悟靜 > 《.net和asp.net》