日期:2011-09-18 浏览次数:20574 次
学习整理了一下
(一). 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 &nb