利用ASP.NET的泛型處理常式(Handler)結合免費的Web Service來產生圖片驗證碼(Image Validate Code)
在近在小舖的文章又看到一個免費的web service
是有關產生圖片驗證碼的web service..還不錯用....
可以用在登入或要輸入表單時的驗證..防止機器人攻擊....
小弟用一個最簡單的範例來說明如何使用此web service
c#範例
免費web service:http://www.webxml.com.cn/WebServices/ValidateCodeWebService.asmx
這個網址是WSDL Scheme的位址
http://www.webxml.com.cn/WebServices/ValidateCodeWebService.asmx?WSDL
先利用 Visual Studio 2005 命令提示字元 將要呼叫web service的類別下載回來...
將產生的ValidateCodeWebService.cs放到App_Code裡...
ValidateImage.aspx
01 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidateImage.aspx.cs" Inherits="web_service_ValidateImage"
02 ContentType="image/Png" %>
03
04 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
05 <html xmlns="http://www.w3.org/1999/xhtml">
06 <head id="Head1" runat="server">
07 <title>ValidateImage</title>
08 </head>
09 <body>
10 <form id="form1" runat="server">
11 <div>
12 <asp:Image ID="Image1" runat="server" ImageUrl="Handler.ashx" /></div>
13 </form>
14 </body>
15 </html>
16
02 ContentType="image/Png" %>
03
04 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
05 <html xmlns="http://www.w3.org/1999/xhtml">
06 <head id="Head1" runat="server">
07 <title>ValidateImage</title>
08 </head>
09 <body>
10 <form id="form1" runat="server">
11 <div>
12 <asp:Image ID="Image1" runat="server" ImageUrl="Handler.ashx" /></div>
13 </form>
14 </body>
15 </html>
16
Handler.ashx
01 <%@ WebHandler Language="C#" Class="Handler" %>
02
03 <%@ WebHandler Language="C#" Class="Handler" %>
04
05 using System;
06 using System.Web;
07
08 public class Handler : IHttpHandler
09 {
10
11 public void ProcessRequest(HttpContext context)
12 {
13
14 ValidateCodeWebService service = new ValidateCodeWebService();
15
16 context.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
17 context.Response.ClearContent();
18 context.Response.ContentType = "image/Png";
19 context.Response.BinaryWrite(service.enValidateByte(""));
20 context.Response.End();
21
22 }
23
24 public bool IsReusable
25 {
26 get
27 {
28 return false;
29 }
30 }
31
32 }
02
03 <%@ WebHandler Language="C#" Class="Handler" %>
04
05 using System;
06 using System.Web;
07
08 public class Handler : IHttpHandler
09 {
10
11 public void ProcessRequest(HttpContext context)
12 {
13
14 ValidateCodeWebService service = new ValidateCodeWebService();
15
16 context.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
17 context.Response.ClearContent();
18 context.Response.ContentType = "image/Png";
19 context.Response.BinaryWrite(service.enValidateByte(""));
20 context.Response.End();
21
22 }
23
24 public bool IsReusable
25 {
26 get
27 {
28 return false;
29 }
30 }
31
32 }
執行結果: