學(xué)習(xí)整理了一下
(一). httphandlers能夠處理對某種特定文件類型的請求.
例如, 在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也非常簡單,下面將創(chuàng)建一個(gè)自定義的httphandler,
功能為驗(yàn)證訪問: *.jpeg/jpg 圖像文件權(quán)限. 通過這個(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.前臺頁面 *.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.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
4
5 <html xmlns="http://www.w3.org/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文件中注冊自己的處理程序類配置
1 <system.web>
2 <httphandlers>
3 <add verb="*" path="*.jpg,*.jpeg" type="jpghandler" />
4 </httphandlers>
5 </system.web>
6
在這里我是將處理程序類 jpghandler.cs 放到 app_code文件夾下面,如果此類不是放在此類下面,而是以程序集*.dll格式的,則應(yīng)該將此程序集放到bin目錄下面,并且這樣配置:
1 <system.web>
2 <httphandlers>
3 <add verb="*" path="*.jpg,*.jpeg" type="jpghandler,yourdll" />
4 </httphandlers>
5 </system.web>
6
(三). 示例代碼下載
http://www.cnblogs.com/files/chengking/jpghttphandler.rar
商業(yè)源碼熱門下載www.html.org.cn
新聞熱點(diǎn)
疑難解答
圖片精選