在一次ASP.NET請求處理過程中,HttpHandler和HttpModule一樣都可以截獲的這個請求并做一些額外的工作。
他們的區(qū)別在于:
(1)對于HTTP請求而言,HttpModule是HTTP請求的“必經(jīng)之路”,HttpModule可以有多個,每次HTTP請求都將逐一通過每個HttpModule。無論客戶端請求什么類型文件,都會調(diào)用HttpModule。
(2)HttpHandler是請求的處理中心,按照你的請求生成響應(yīng)的內(nèi)容。可自定義什么情況下調(diào)用HttpHandler。
(3)ASP.Net處理請求時,使用(管道)方式,由各個HttpModule對請求進(jìn)行處理,然后到達(dá) HttpHandler,HttpHandler處理完之后,再交給HttpModule處理,最后將HTML發(fā)送到客戶端瀏覽器中。HttpModule中的事件有的在HttpHandler之前,有的在之后。
一、HttpHandler實現(xiàn)驗證碼
0094.PNG
在項目中創(chuàng)建一般處理程序文件“ValidateImageHandle.ashx”。
<%@ WebHandler Language="C#" Class="ValidateImageHandle" %>
using System;
using System.Web;
using System.Drawing;
/*
HttpHandler中默認(rèn)是不能使用Session的。
解決方法:
1、讀取Session時:實現(xiàn)System.Web.SessionState.IReadOnlySessionState接口,無任何方法(只是一個標(biāo)記作用)
2、保存Session時:實現(xiàn)System.Web.SessionState.IRequiresSessionState接口
*/
public class ValidateImageHandle : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public void ProcessRequest (HttpContext context) {
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
string strCode = CreateRnd();
context.Session["validate"] = strCode;
byte[] bytes = CreateImage(strCode);
context.Response.ContentType = "image/gif";
context.Response.BinaryWrite(bytes);
}
public bool IsReusable {
get {
return false;
}
}
#region 生成隨機(jī)驗證碼
public string CreateRnd()
{
Random Rnd = new Random();
string RndChars = "";
char code;
for (int i = 1; i <= 4; i++)
{
if (Rnd.Next() % 2 == 0) //偶數(shù)生成數(shù)字
{
code = (char)('0' + Rnd.Next(0, 10));
}
else //奇數(shù)生成字母
{
code = (char)('A' + Rnd.Next(0, 10));
}
RndChars = RndChars + code.ToString();
}
return RndChars;
}
#endregion
#region 將驗證碼生成圖片
public byte[] CreateImage(string RndChars)
{
Random Rnd = new Random();
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(RndChars.Length * 15, 26);
Graphics g = Graphics.FromImage(bitmap);
g.Clear(Color.Gray); //清空圖片,設(shè)置背景為灰色
//畫圖片噪線
for (int i = 1; i <= Rnd.Next(10, 30); i++)
{
int x1 = Rnd.Next(1, bitmap.Width);
int x2 = Rnd.Next(1, bitmap.Width);
int y1 = Rnd.Next(1, bitmap.Height);
int y2 = Rnd.Next(1, bitmap.Height);
g.DrawLine(new Pen(Color.Green), x1, y1, x2, y2);
}
//畫驗證碼字符串
Font font = new Font("微軟雅黑", 12, (FontStyle.Bold | FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new RectangleF(0, 0, bitmap.Width, bitmap.Height), Color.Red, Color.Blue, 1.2f, true);
g.DrawString(RndChars, font, brush, 2, 2);
//畫圖片噪點
for (int i = 0; i <= Rnd.Next(50, 100); i++)
{
int x = Rnd.Next(1, bitmap.Width);
int y = Rnd.Next(1, bitmap.Height);
bitmap.SetPixel(x, y, Color.Red);
}
//畫圖片邊框線
g.DrawRectangle(new Pen(Color.Black), 0, 0, bitmap.Width - 1, bitmap.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
#endregion
}
用戶登錄使用驗證碼:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>httpHandler實現(xiàn)驗證碼</title>
<script src="js/jquery.js" type="text/javascript"></script>
<style type="text/css">
#container{ text-align:center;}
.righttd
{
width: 460px;
}
.lefted
{
width: 196px;
}
.mytitle{ font-size:18px; font-weight:bold;}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
//alert(new Date());
$(function () {
$("#Refresh").click(function () {
$("#imgValidate").prop("src", "ValidateImageHandle.ashx?date=" + new Date());
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>httpHandler實現(xiàn)驗證碼-先復(fù)習(xí)之前案例中驗證碼的實現(xiàn)</h1>
<table>
<tr>
<td align="center" height="30" class="mytitle" colspan="2">用戶登錄</td>
</tr>
<tr>
<td align="right" class="lefted" height="30">用戶名:</td>
<td align="left" class="righttd" height="30">
<asp:TextBox ID="txtAccount" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" class="lefted" height="30">密碼:</td>
<td align="left" class="righttd" height="30">
<asp:TextBox ID="txtPwd" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" class="lefted" height="30">驗證碼:</td>
<td align="left" class="righttd" height="30">
<asp:TextBox ID="txtValidate" runat="server" Width="72px"></asp:TextBox>
<asp:Image ID="imgValidate" runat="server" ImageUrl="~/ValidateImageHandle.ashx" />
<a href="javascript:void(0);" id="Refresh">刷新</a>
</td>
</tr>
<tr>
<td align="right" class="lefted" height="30"></td>
<td align="left" class="righttd" height="30">
<asp:Button ID="btLogin" runat="server" Text="登 錄" onclick="btLogin_Click" />
</td>
</tr>
<tr>
<td align="right" class="lefted" height="30"></td>
<td align="left" class="righttd" height="30">
<asp:Label ID="lblErrInfo" runat="server" ForeColor="Red"></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
public partial class Demo01 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region 登錄
protected void btLogin_Click(object sender, EventArgs e)
{
if (Session["validate"] == null)
{
this.lblErrInfo.Text = "驗證碼過期";
this.imgValidate.ImageUrl = "~/ValidateImageHandle.ashx"; //加載驗證碼
return;
}
if (this.txtValidate.Text.Equals(Session["validate"].ToString()) == false)
{
this.lblErrInfo.Text = "驗證碼錯誤!";
}
else
{
this.lblErrInfo.Text = "驗證碼正確";
}
}
#endregion
}
二、HttpHandler實現(xiàn)圖片水印
HttpHandler實現(xiàn)圖片水印在此文中有兩種方式來實現(xiàn):
(1)創(chuàng)建ashx文件進(jìn)行二次繪圖,C#程序中調(diào)用ashx文件實現(xiàn)水印添加。
(2)創(chuàng)建CS類文件進(jìn)行二次繪圖,通過配置文件配置路徑規(guī)則給指定路徑下的文件實現(xiàn)水印添加。
方案一
在項目中創(chuàng)建一般處理程序文件“ImgHandler.ashx”。
<%@ WebHandler Language="C#" Class="ImgHandler" %>
using System;
using System.Web;
using System.Drawing;
public class ImgHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
string vpath = context.Request.QueryString["ImageUrl"]; //虛擬路徑
string ppath = context.Server.MapPath(vpath); //根據(jù)虛擬路徑獲得物理路徑
Image img = Image.FromFile(ppath); //根據(jù)絕對路徑獲取圖片
Graphics gh = Graphics.FromImage(img); //繪畫對象
Image imgWaterMark = Image.FromFile(context.Server.MapPath("~/img/watermark.png"));
float w = img.Width;
float h = img.Height;
float x = 6;
float y = 6;
gh.DrawImage(imgWaterMark, x, y, w, h); //進(jìn)行二次繪圖
context.Response.ContentType = "image/jpeg";
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
public bool IsReusable {
get {
return false;
}
}
}
頁面中實現(xiàn)圖片水印:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>httpHandle給圖片添加水印</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="pnlImages" runat="server">
<asp:Image ID="Image2" runat="server" Width="200" Height="240" ImageUrl="~/img/book/5566e4b4Nb156fe14.jpg" />
<asp:Image ID="Image3" runat="server" Width="200" Height="240" ImageUrl="~/img/book/5573e4b4Nb1561288.jpg" />
<asp:Image ID="Image5" runat="server" Width="200" Height="240" ImageUrl="~/img/book/55b8a409N20918431.jpg" />
<asp:Image ID="Image6" runat="server" Width="200" Height="240" ImageUrl="~/img/book/9787020096466.jpg" />
<asp:Image ID="Image7" runat="server" Width="200" Height="240" ImageUrl="~/img/book/9787020096473.jpg" />
</asp:Panel>
</div>
</form>
</body>
</html>
public partial class Demo02 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
foreach (Control obj in pnlImages.Controls)
{
Image img = obj as Image;
if (img != null)
{
string imgurl = img.ImageUrl;
img.ImageUrl = "~/ImgHandler.ashx?ImageUrl=" + Server.UrlEncode(imgurl);
}
}
}
}
方案二
在App_Code文件夾創(chuàng)建“MyImgHandler.cs”文件。
public class MyImgHandler:IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
string vpath = context.Request.Path; //獲取配置文件中配置的路徑
string ppath = context.Server.MapPath(vpath); //根據(jù)虛擬路徑獲得物理路徑
Image img = Image.FromFile(ppath); //根據(jù)絕對路徑獲取圖片
Graphics gh = Graphics.FromImage(img); //繪畫對象
Image imgWaterMark = Image.FromFile(context.Server.MapPath("~/img/watermark.png"));
float w = img.Width;
float h = img.Height;
float x = 6;
float y = 6;
gh.DrawImage(imgWaterMark, x, y, w, h); //進(jìn)行二次繪圖
//context.Response.ContentType = "image/jpeg";
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
public bool IsReusable
{
get
{
return false;
}
}
}
根目錄web.config配置文件:
<?xml version="1.0"?>
<!--
有關(guān)如何配置 ASP.NET 應(yīng)用程序的詳細(xì)信息,請訪問
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<!--IIS6配置-->
<httpHandlers>
<add type="MyImgHandler" path="img/book/*.*" verb="*"/>
</httpHandlers>
</system.web>
<!--IIS7配置-->
<!--<system.webServer>
<handlers>
<add name="MyImgHandler" path="img/book/*.*" type="MyImgHandler" verb="*"/>
</handlers>
</system.webServer>-->
</configuration>
頁面測試水印效果:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>httpHandle給圖片添加水印-將Handle寫在類文件中用配置文件來調(diào)用</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="pnlImages" runat="server">
<asp:Image ID="Image2" runat="server" Width="200" Height="240" ImageUrl="~/img/book/5566e4b4Nb156fe14.jpg" />
<asp:Image ID="Image3" runat="server" Width="200" Height="240" ImageUrl="~/img/book/5573e4b4Nb1561288.jpg" />
<asp:Image ID="Image5" runat="server" Width="200" Height="240" ImageUrl="~/img/book/55b8a409N20918431.jpg" />
<asp:Image ID="Image6" runat="server" Width="200" Height="240" ImageUrl="~/img/book/9787020096466.jpg" />
<asp:Image ID="Image7" runat="server" Width="200" Height="240" ImageUrl="~/img/book/9787020096473.jpg" />
</asp:Panel>
</div>
<div>
<asp:Image ID="Image1" runat="server" Width="200" Height="240" ImageUrl="~/img/nba/lunnade.jpg" />
<asp:Image ID="Image4" runat="server" Width="200" Height="240" ImageUrl="~/img/nba/maidi.jpg" />
<asp:Image ID="Image8" runat="server" Width="200" Height="240" ImageUrl="~/img/nba/nashi.jpg" />
</div>
</form>
</body>
</html>