给BlogEngine.Net添加上验证码

by Admin1. February 2010 05:31

 本文转自:吴鹏的博客 给BlogEngine.Net添加上验证码 文章链接:http://wupeng.cn/post/2009/08/27/Add-Captcha-to-BlogEnginenet-Chinese.aspx
最近老是受到垃圾评论的骚扰,我是开启了有评论进行邮件提示,有一天竟然有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);
     }

4.不足

按照上面的方法虽然加上了注册码,仍有不足
1.验证码,不能刷新,提示语不自动消失
2.评论提交验证不足

5.稍微改进

针对上面
1.修改blog.js,加上刷新验证码(非ajax),去除提示

            if (!BlogEngine.comments.moderation)
                BlogEngine.$("status").innerHTML = BlogEngine.i18n.commentWasSaved;
            else
                BlogEngine.$("status").innerHTML = BlogEngine.i18n.commentWaitingModeration;
            document.getElementById('img').src = document.getElementById('img').src + "?t=" + Math.random(); //by zsk 刷新验证码
            document.getElementById("CaptchaMsg").innerHTML = "";//by zsk 消除提示语

2.严谨下提交评论,提交时判断验证,仍然修改blog.js

    validateAndSubmitCommentForm: function() {
var bBuiltInValidationPasses = Page_ClientValidate('AddComment');
var bNameIsValid = BlogEngine.comments.nameBox.value.length > 0;
document.getElementById('spnNameRequired').style.display = bNameIsValid ? 'none' : '';
var bAuthorNameIsValid = true;
if (BlogEngine.comments.checkName) {
var author = BlogEngine.comments.postAuthor;
var visitor = BlogEngine.comments.nameBox.value;
bAuthorNameIsValid = !this.equal(author, visitor);
}
DoCheckCaptcha();//by zsk 再次检查验证
document.getElementById('spnChooseOtherName').style.display = bAuthorNameIsValid ? 'none' : '';
if (bBuiltInValidationPasses && bNameIsValid && bAuthorNameIsValid && checkCaptchaResult) {//by zsk 判断验证是否通过
BlogEngine.addComment();
return true;
}
return false;
}

通过以上两步稍微修改,有一点点改进,基本达到能用的程度,加上系统带的垃圾邮件管理,利用白名单,黑名单来遏制垃圾邮件,是个不错的选择

Tags: , ,

.Net | JS

Add comment

  Country flag

biuquote
Loading

我的饭否

Widget RandomPosts not found.

The file '/blog/widgets/RandomPosts/widget.ascx' does not exist.X

RecentComments

Comment RSS

Google PageRank