ValidNumber
ashx 代碼
<%@ WebHandler Language=
C#
Class=
ValidNumber
%>
using System;
using System
Web;
using System
Web
SessionState; //第一步
導入此命名空間
public class ValidNumber : IHttpHandler
IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
//種子
string[] strlist = new[]
{
a
b
c
d
q
w
e
r
t
y
u
i
o
p
z
x
n
v
W
Q
B
A
D
D
F
G
H
J
K
L
};
//生成隨機數
string[] list = new string[
];
Random rd = new Random(DateTime
Now
Millisecond *
)
for (int i =
; i <
; i++)
{
list[i] = strlist[rd
Next(strlist
Length)];
System
Threading
Thread
Sleep(
)
}
System
Text
StringBuilder sb = new System
Text
StringBuilder()
for (int i =
; i <
; i++)
{
sb = sb
Append(list[i])
}
HttpContext
Current
Session[
validNumber
] = sb;
//創建一張圖片
System
Drawing
Bitmap image = new System
Drawing
Bitmap(list
Length *
)
//創建畫布
System
Drawing
Graphics g = System
Drawing
Graphics
FromImage(image)
//清空背景色
並添充成白色
g
Clear(System
Drawing
Color
White)
//噪聲線
for (int i =
; i <
; i++)
{
Random rds = new Random()
float x
= rds
Next(image
Width
)
float x
= rds
Next(image
Width
)
float y
= rds
Next(image
Height
)
float y
= rds
Next(image
Height
)
System
Threading
Thread
Sleep(
)
g
DrawLine(new System
Drawing
Pen(System
Drawing
Color
Silver)
x
y
x
y
)
}
System
Drawing
Font f = new System
Drawing
Font(
黑體
System
Drawing
GraphicsUnit
Pixel)
System
Drawing
Brush bs = new System
Drawing
SolidBrush(System
Drawing
Color
Red)
g
DrawString(sb
ToString()
f
bs
)
//當前請求輸出的類型
HttpContext
Current
Response
ContentType =
image/jpeg
;
//保存到輸出流
image
Save(HttpContext
Current
Response
OutputStream
System
Drawing
Imaging
ImageFormat
Jpeg)
g
Dispose()
image
Dispose()
}
public bool IsReusable
{
get
{
return false;
}
}
}
頁面調用時 <img src=
ValidNumber
ashx
alt=
圖片驗證碼
/> 但是回發session值改變頁面圖片沒變
暫無比較理想的解決辦法
提交時後台用 Response
Write(
<script> window
location
href=window
location
href</script>
) 刷新下頁面
From:http://tw.wingwit.com/Article/program/net/201311/13143.html