给BlogEngine.Net添加上验证码

by Alpha 27. August 2009 10:27

最近老是受到垃圾评论的骚扰,我是开启了有评论进行邮件提示,有一天竟然有100多个提示,而且都是垃圾评论,不堪其扰啊。Google了一下,给BlogEngine加验证码的文章并不是很多,Keith Ratliff写了一个用reChaptcha的文章(I Have Added reCaptcha to My BlogEngine.Net Blog!),不过实现起来太复杂,而且把Ajax去掉了,每次留言都会刷新,感觉不太好。

下面说一下我的解决方法:

English Version is here:http://wupeng.cn/post/2009/08/27/Add-Captcha-to-BlogEngineNet.aspx

1.首先,写生成一个验证码的文件(Image.aspx),当然也可以搜索去找,我从CSDN下载的一个,代码如下:

Image.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Image.aspx.cs" Inherits="Image" %>

Image.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Drawing2D;
public partial class Image : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CreateCheckCodeImage(GenCode(4));
    }
    /**/
    /// <summary>
    /// '产生随机字符串
    /// </summary>
    /// <param name="num">随机出几个字符</param>
    /// <returns>随机出的字符串</returns>
    private string GenCode(int num)
    {
        //  string str = "的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府称太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严";
        //   char[] chastr = str.ToCharArray();
        string[] source ={ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
        string code = "";
        Random rd = new Random();
        int i;
        for (i = 0; i < num; i++)
        {
            code += source[rd.Next(0, source.Length)];
            //  code += str.Substring(rd.Next(0, str.Length), 1);
        }
        return code;

    }

    /**/
    /// <summary>
    /// 生成图片(增加背景噪音线、前景噪音点)
    /// </summary>
    /// <param name="checkCode">随机出字符串</param>
    private void CreateCheckCodeImage(string checkCode)
    {
        if (checkCode.Trim() == "" || checkCode == null)
            return;
        Session["AlphaCaptchaCode"] = checkCode; //将字符串保存到Session中,以便需要时进行验证
        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)(checkCode.Length * 19), 22);
        Graphics g = Graphics.FromImage(image);
        try
        {
            //生成随机生成器
            Random random = new Random();

            //清空图片背景色
            g.Clear(Color.White);

            // 画图片的背景噪音线
            int i;
            for (i = 0; i < 25; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);
                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }

            Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, true);
            g.DrawString(checkCode, font, brush, 4, 1);

            //画图片的前景噪音点
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/jpg";
            Response.BinaryWrite(ms.ToArray());

        }
        catch
        {
            g.Dispose();
            image.Dispose();
        }

    }
}
这个程序生成的验证码比较简单,容易辨认。

 

2.修改CommentView.ascx,我直接给出Diff文件。

--- C:\Users\ADMINI~1\AppData\Local\Temp\2\CommentView.ascx-rev5.svn000.tmp.ascx	四 八月 27 09:58:04 2009
+++ C:\Users\ADMINI~1\AppData\Local\Temp\2\CommentView.ascx-rev6.svn000.tmp.ascx	四 八月 27 09:58:04 2009
@@ -48,7 +48,11 @@
 	  <asp:DropDownList runat="server" ID="ddlCountry" onchange="BlogEngine.setFlag(this.value)" TabIndex="5" EnableViewState="false" ValidationGroup="AddComment" />&nbsp;
 	  <asp:Image runat="server" ID="imgFlag" AlternateText="Country flag" Width="16" Height="11" EnableViewState="false" /><br /><br />
 	  <%} %>
-
+    
+      <label for="<%=txtCaptcha.ClientID %>">验证码*</label>
+      <img src="/Image.aspx" alt="看不清?点击图片看看" style="width: 82px; height: 23px" onclick="this.src=RefreshCaptcha(this.src)" />
+      <asp:TextBox runat="Server" ID="txtCaptcha" TabIndex="4" MaxLength="4" Width="60px" onblur="DoCheckCaptcha()"/><span id="CaptchaMsg"></span><asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtCaptcha" ErrorMessage="<%$Resources:labels, required %>" Display="dynamic" ValidationGroup="AddComment" /><br />
+      
 	  <span class="bbcode" title="BBCode tags"><%=BBCodes() %></span>
 	  <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtContent" ErrorMessage="<%$Resources:labels, required %>" Display="dynamic" ValidationGroup="AddComment" /><br />
 
@@ -70,7 +74,7 @@
 	  <input type="checkbox" id="cbNotify" style="width: auto" tabindex="7" />
 	  <label for="cbNotify" style="width:auto;float:none;display:inline"><%=Resources.labels.notifyOnNewComments %></label><br /><br />
 	 
-	  <input type="button" id="btnSaveAjax" value="<%=Resources.labels.saveComment %>" onclick="if(Page_ClientValidate('AddComment')){BlogEngine.addComment()}" tabindex="7" />    
+	  <input type="button" id="btnSaveAjax" value="<%=Resources.labels.saveComment %>" onclick="if(Page_ClientValidate('AddComment')&&checkCaptchaResult){BlogEngine.addComment()}" tabindex="7" />    
 	  <asp:HiddenField runat="server" ID="hfCaptcha" />
 	</div>
 
@@ -90,7 +94,7 @@
 	BlogEngine.comments.countryDropDown = BlogEngine.$("<%=ddlCountry.ClientID %>"); 
 	BlogEngine.comments.captchaField = BlogEngine.$('<%=hfCaptcha.ClientID %>');
 	BlogEngine.comments.controlId = '<%=this.UniqueID %>';
-	BlogEngine.comments.replyToId = BlogEngine.$("<%=hiddenReplyTo.ClientID %>"); 
+	BlogEngine.comments.replyToId = BlogEngine.$("<%=hiddenReplyTo.ClientID %>");
 }
 //-->
 </script>
@@ -116,4 +120,39 @@
 <%} %>
 </asp:PlaceHolder>
 
+
+<script type="text/javascript">
+    
+        function DoCheckCaptcha() {
+            var code = document.getElementById("<%=txtCaptcha.ClientID %>").value;
+            checkCaptcha(code);
+        }
+        var checkCaptchaResult=false;
+        function ReceiveServerData(CheckResult) {
+            document.getElementById("CaptchaMsg").innerHTML = "";
+            if (CheckResult == 1) {
+                checkCaptchaResult = true;
+                document.getElementById("CaptchaMsg").innerHTML = "<font color=green>验证码正确!</font>";
+            }
+            else if (CheckResult == -1) {
+                checkCaptchaResult = false;
+                //document.getElementById("CaptchaMsg").innerHTML = "<font color=red>验证码错误!</font>";
+            }
+            else {
+                checkCaptchaResult = false;
+                document.getElementById("CaptchaMsg").innerHTML = "<font color=red>验证码错误!</font>";
+            }
+        }
+        function RefreshCaptcha(url) {
+            if (url.toString().indexOf("?",0) > 0) {
+                url = url.toString().substring(0, url.toString().indexOf("?", 0)) + "?" + new Date().toUTCString();
+            }
+            else{
+                url = url.toString() + "?" + new Date().toUTCString();
+            }
+            return url;
+            
+        }
+    </script>
+
 <asp:label runat="server" id="lbCommentsDisabled" visible="false"><%=Resources.labels.commentsAreClosed %></asp:label>
\ No newline at end of file

3.修改CommentView.ascx.cs,直接给Diff文件

--- C:\Users\ADMINI~1\AppData\Local\Temp\2\CommentView.ascx.cs-rev5.svn000.tmp.cs	四 八月 27 10:21:21 2009
+++ C:\Users\ADMINI~1\AppData\Local\Temp\2\CommentView.ascx.cs-rev6.svn000.tmp.cs	四 八月 27 10:21:21 2009
@@ -41,6 +41,25 @@
 	/// <param name="eventArgument">A string that represents an event argument to pass to the event handler.</param>
 	public void RaiseCallbackEvent(string eventArgument)
 	{
+        if (eventArgument.Length < 1)
+        {
+            _Callback = "-1";
+            return;
+        }
+        if (eventArgument.LastIndexOf("-|-") < 0)
+        {
+            string img = Session["AlphaCaptchaCode"].ToString().ToLower(); ;
+            if (eventArgument.ToLower().Equals(img))
+            {
+                _Callback = "1";
+            }
+            else
+            {
+                _Callback = "0";
+            }            
+            return;
+        }
+
 		if (!BlogSettings.Instance.IsCommentsEnabled)
 			return;
 
@@ -196,9 +215,13 @@
 				phAddComment.Visible = false;
 			}
 			//InititializeCaptcha();
-		}
+            string cbReference = Page.ClientScript.GetCallbackEventReference(this, "CheckResult", "ReceiveServerData", "");   //获取一个对客户端函数的引用;调用该函数时,将启动一个对服务器端事件的客户端回调。
+            string callbackScript = "function checkCaptcha(CheckResult){" + cbReference + ";}";                                        //注册客户端方法
+            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "checkCaptcha", callbackScript, true); 
 
+		}//end ispostback
 
+
 		Page.ClientScript.GetCallbackEventReference(this, "arg", null, string.Empty);
 	}
 

Tags: , Views:2644

BlogEngine.NET

Comments

11/7/2009 5:27:47 PM #

liqy520

好东东,支持了。

liqy520 People's Republic of China |

11/9/2009 11:02:38 PM #

soief

谢谢 值得学习

soief People's Republic of China |

11/16/2009 11:38:00 PM #

李西强

很好 谢谢
我的也加了浏览次数了。 跟你多学学

李西强 People's Republic of China |

11/17/2009 10:31:39 AM #

Alpha

相互交流,国内用BE的人不多。

Alpha People's Republic of China |

2/1/2010 2:07:57 AM #

zsk

前来学习...

zsk People's Republic of China |

3/4/2010 3:19:07 AM #

trackback

给BlogEngine.Net添加上验证码

给BlogEngine.Net添加上验证码

神秘园 CaBeta.com |

4/23/2010 3:01:55 PM #

Nike air jordan shoes

       goo

Nike air jordan shoes People's Republic of China |

5/2/2010 4:48:14 PM #

guest

谢谢分享

guest People's Republic of China |

5/10/2010 6:19:17 PM #

banjarmasin

thanks about your post. very gud.

banjarmasin Indonesia |

5/31/2010 5:01:32 PM #

adidas outlet shoes

Very vivid appearance, perfect plot, challenging game. Many of us put this game as a very important part of life. Surprise,when I browse the web ,I found these website Pretty good. such as go and see it that rich variety of fashion at a reasonable price !

adidas outlet shoes People's Republic of China |

6/2/2010 6:53:32 PM #

高尔夫模拟器

博主的文章很精彩,mark一下

高尔夫模拟器 People's Republic of China |

6/3/2010 6:39:36 PM #

二手挖掘机

博主的妙文,我客气地收下了,哈哈。

二手挖掘机 People's Republic of China |

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen  浙ICP备09023819号  

关于作者

Alpha

1.男
2.已婚
3.网虫
4.宝宝叫yoyo

Calendar

<<  September 2010  >>
MondayTuesdayWednesdayThursdayFridaySaturdaySunday
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

RecentComments

Comment RSS