asp.net| Example | download
Learn to tidy up a bit
(i). HttpHandlers can handle requests for a particular file type.
For example, in the Machine.config file, the default already has most of the system processing handlers:
<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 "/>
.......
Creating a HttpHandler is also very simple, and the following will create a custom HttpHandler,
function for authenticated access: *.jpeg/jpg image file permissions. Use this example to illustrate its usage.
(b). The code is as follows
1. Handler HttpHandler file JpgHandler.cs code
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
One///<summary>
12///only users with admin privileges can view images of JPG and JPEG directly
///</summary>
public class Jpghandler:ihttphandler
15 {
Public Jpghandler ()
17 {
18}
public void ProcessRequest (HttpContext hc)
20 {
String strFileName = HC. Server.MapPath (HC. Request.filepath);
if (HC). User.IsInRole ("admin"))//Whether the current user is admin right
23 {
HC. Response.ContentType = "Image/jpeg";
HC. Response.WriteFile (strFileName);
26}
/Else
28 {
HC. Response.ContentType = "Image/jpeg";
HC. Response.Write ("No right");
31}
32}
public bool IsReusable
34 {
# get
36 {
Panax Notoginseng return true;
38}
39}
40}
41
2. Front Page *.aspx Code
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 6 7 <title>httphandler Validate Users right</title>
8 9 <body>
<form id= "Form1" runat= "Server" >
<div>
<asp:linkbutton id= "LinkButton1" runat= "Server" postbackurl= "A.jpeg" tooltip= "click me!" Width= "149PX" >A.jpeg</asp:LinkButton>
13
</div>
</form>
</body>
18
3. Register your own handler class configuration in the Web.config file
1 <system.web>
2 3 <add verb= "*" path= "*.jpg,*.jpeg" type= "Jpghandler"/>
4 5 </system.web>
6
Here I am putting the handler class JpgHandler.cs under the App_Code folder, if this class is not placed under this class, but in an assembly *.dll format, you should put this assembly under the Bin directory and configure this:
1 <system.web>
2 3 <add verb= "*" path= "*.jpg,*.jpeg" type= "Jpghandler,yourdll"/>
4 5 </system.web>
6
(iii). Sample code Download
Http://www.cnblogs.com/Files/ChengKing/JpgHttpHandler.rar