Asp.net MVC Razor Html Helper ile Captcha

Basit kullanımlı, basit bir captcha ihtiyacımı karşılamak için geliştirdiğim kod blokları aşağıda ki gibidir.

Razor olarak kullanmak için Html Extensions

    public static partial class HtmlExtensions
    {
        public static MvcHtmlString Captcha(this HtmlHelper helper)
        {
            string result = string.Empty;

            var panel = new TagBuilder("div");
            panel.Attributes.Add("class", "panel panel-default");

            var mainDiv = new TagBuilder("div");
            mainDiv.Attributes.Add("id", "captchaHtmlExtensions");
            mainDiv.Attributes.Add("ct-captcha", "");

            var imageDiv = new TagBuilder("div");
            imageDiv.Attributes.Add("id", "captchaImage");
            imageDiv.Attributes.Add("class", "col-md-12");
            imageDiv.Attributes.Add("onclick", "getCaptchaImage()");

            var input = new TagBuilder("input");
            input.Attributes.Add("name", "captchaValue");
            input.Attributes.Add("id", "captchaValue");
            input.Attributes.Add("class", "form-control");
            input.Attributes.Add("type", "form-text");
            input.Attributes.Add("placeholder", "Kodu Giriniz");

            var text = new TagBuilder("h6");
            text.InnerHtml = "Doğrulama Kodu";
            text.Attributes.Add("class", "panel-heading panel-title");

            panel.InnerHtml += text.ToString();
            panel.InnerHtml += mainDiv.ToString();
            panel.InnerHtml += imageDiv.ToString();
            panel.InnerHtml += input.ToString();

            result += panel.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(result);
        }
    }

base64 olarak geri dönen captcha image methodu:

        public static string GetCaptchaImageByBase64()
        {
            bool noisy = true;
            var random = new Random((int)DateTime.Now.Ticks);

            int imageWidth = 100;
            int imageHeight = 30;

            //generate text
            int length = 3;
            string characters = "ABCDEFGHIJKLMNOPRSTUVYZ";
            StringBuilder result = new StringBuilder(length);
            for (int i = 0; i < length; i++)
            {
                result.Append(characters[random.Next(characters.Length)]);
            }

            //generate text

            var captcha = result.ToString();

            //result
            HttpContext.Current.Session["CaptchaImageResult"] = result.ToString();

            //captchaImage

            using (var mem = new MemoryStream())
            using (var bmp = new Bitmap(imageWidth, imageHeight))
            using (var gfx = Graphics.FromImage((Image)bmp))
            {
                gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                gfx.SmoothingMode = SmoothingMode.AntiAlias;
                gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));

                if (noisy)
                {
                    int i, r, x, y;
                    var pen = new Pen(Color.Yellow);
                    for (i = 1; i < 8; i++)
                    {
                        pen.Color = Color.FromArgb(
                        (random.Next(0, 255)),
                        (random.Next(0, 255)),
                        (random.Next(0, 255)));

                        r = random.Next(0, (imageWidth / 3));
                        x = random.Next(0, imageWidth);
                        y = random.Next(0, imageHeight);

                        gfx.DrawEllipse(pen, x - r, y - r, r, r);
                    }
                }

                //image add text
                gfx.DrawString(captcha, new Font("Tahoma", 18), Brushes.Gray, 15, 3);

                //generate image stream
                bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Png);
                string srcValue = string.Format("data:image/png;base64, {0}", Convert.ToBase64String(mem.ToArray()));

                return srcValue;
            }
        }

Oluşan captcha image’nı json olarak döndüren method:

        public ActionResult GetCaptchaImageJson()
        {
            return Json(Operations.GetCaptchaImageByBase64(), JsonRequestBehavior.AllowGet);
        }

Javascript function:

$(document).ready(function () {
    $("div").each(function () {

        if ($(this).attr("ct-Captcha") != undefined) {
            getCaptchaImage();

            $("#captchaValue").bind('keyup', function (e) {
                if (e.which >= 97 && e.which <= 122) {
                    var newKey = e.which - 32;
                    e.keyCode = newKey;
                    e.charCode = newKey;
                }
                $("#captchaValue").val(($("#captchaValue").val()).toUpperCase());
            });
        }
    });
});
function getCaptchaImage() {
    $.ajax({
        cache: false,
        async: true, //!!!
        type: "POST",
        url: pureRoot + "Json/GetCaptchaImageJson",
        success: function (data) {
            //console.log(data, "UTIL -> getCaptchaImage -> success");
            $('#captchaImage').html('<div style="margin:5px;"><img src="' + data + '" class="img-responsive" title="Yenilemek için tıklayınız"/></div>')
            $("#captchaValue").val('');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log("Bağlantı sırasında hata oluştu!", "UTIL -> getCaptchaImage -> error");
        }
    });
}

Kullanımı:

@Html.Captcha()

Captcha

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir