asp.net|示例|下载
学习整理了一下
(一). HttpHandlers能够处理对某种特定文件类型的请求.
例如, 在machine.config 文件中默认已经有大部分的系统处理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>
创建一个HttpHandler也非常简单,下面将创建一个自定义的HttpHandler,
功能为验证访问: *.jpeg/jpg 图像文件权限. 通过这个示例演示其用法.
(二).代码如下
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 权限用户才能直接查看 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")) //当前用户是否为 admin 权限
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!" 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格式的,则应该将此程序集放到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