Add Multiple reCAPTCHA Google in single page C# asp.net MVC

Thảo luận trong 'Lập Trình Website MVC5 & MVC6' bắt đầu bởi admin, 1/9/18.

  1. admin
    Tham gia ngày:
    22/5/13
    Bài viết:
    4,894
    Đã được thích:
    1,198
    Điểm thành tích:
    113
    Giới tính:
    Nam
    Để add 1 reCAPTCHA khá đơn giản trong ASP.NET MVC, nhưng để add nhiều Add Multiple reCAPTCHA Google in Single Page C# asp.net MVC (thêm 2 hoặc nhiều reCAPTCHA của google trên một webpage) việc thêm này không phải ai cũng biết và cách hoạt động của nó. Vì trên mạng chỉ nhiều nhưng không phải lúc nào cũng làm được và hầu như chỉ cho PHP khá nhiều, còn asp.net thì hầu như có nhưng không hoạt động.

    Demo link: https://pharma360.vn/lien-he/

    Demo hình:

    add-2-hoac-nhieu-recaptcha-vao-1-webpage-single-webpage.jpg

    Để thêm 1 hoặc nhiều reCAPTCHA vào 1 webpage các bạn làm như sau:

    Bước 1: Tạo tài khoản reCaptcha của google để lấy mã về.

    Trước tiên bạn vào link dưới, để đăng ký với reCaptcha Google và tạo Site keySecret key
    • Khi khai báo xong và tạo thành công sẽ có 2 mã như dưới.
    site-key-secret-key-recapcha-google.jpg
    • Tiếp theo vào Web.config của bạn chèn vào như sau: Để muốn lấy ra từ web.config còn không thì thôi
    Mã:
    <appSettings>
        <!-- Recaptcha -->
        <add key="recaptchaPublickey" value="Mã Site key"/>
        <add key="recaptchaPrivatekey" value="Mã Secret key"/>
        <!-- ConfigurationManager.AppSettings["recaptchaPublickey"] -->
    </appSettings>
    Bước 2: Tạo 1 class trong Models có tên CaptchaResponse.cs
    • Class này sẽ lấy dữ liệu được trả về khi truyền vào Controllers.
    • Code trong Models
    Mã:
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace MyNamesPace.Models
    {
        public class CaptchaResponse
        {
            [JsonProperty("success")]
            public bool Success { get; set; }
            [JsonProperty("error-codes")]
            public List<string> ErrorMessage { get; set; }
        }
    }
    
    Bước 3: Đưa reCaptcha lên View
    • Tạo 1 view để đưa reCaptcha vào đó ví dụ mình tạo View: Contact.cshtml trong Controller Home.
    HTML:
    @{
        ViewBag.Title = "Liên hệ";
    }
    <div class="container">
    @Html.ValidationSummary()
    @using (Html.BeginForm("Contact1", "Home", FormMethod.Post, new { id = "frmContact1", name = "frmContact1" }))
    {
        <div class="row">
            @Html.TextBoxFor("Name1", "" ,new { placeholder = "Họ và tên (bắt buộc)", @class = "form-control cs-textsearch" })
        </div>
        <div class="row">
            @Html.TextBoxFor("Email1","", new { placeholder = "Địa chỉ Email (bắt buộc)", @class = "form-control cs-textsearch" })
        </div>
        <div class="row">
            <div id="recaptchaContact1"></div>
        </div>
        <div class="row">                    
            <div id="btnSend1" class="inputButton">Gửi ngay</div>
        </div>
    }
    </div>  
    <div class="container">
    @Html.ValidationSummary()
    @using (Html.BeginForm("Contact2", "Home", FormMethod.Post, new { name = "frmContact2" }))
    {
        <div class="row">
            @Html.TextBoxFor("Name2", "" , new { placeholder = "Họ và tên (bắt buộc)", @class = "form-control cs-textsearch" })
    
        </div>
        <div class="row">
            @Html.TextBoxFor("Email2", "" , new { placeholder = "Địa chỉ Email (bắt buộc)", @class = "form-control cs-textsearch" })
        </div>
        <div class="row" style="margin-bottom: 5px;">
            <div id="recaptchaContact2"></div>
            <!--Vì trên 1 page 2 recaptcha nên phải lưu response của recaptcha 2 vào biến lấy ra khi button from được click -->
            @Html.Hidden("recaptchavalue","")
        </div>
        <div class="row" style="margin-top: 5px;">
            <div id="btnSend2" class="inputButton">Gửi yêu cầu</div>
        </div>
    }
    </div>
    <script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit&hl=vi" async defer></script>
    <script>
        //xử lý cho recaptcha thứ 2, recaptcha thứ 1 thực hiện bình thường
        var verifyCallback = function (response) {
            if (response != '')
            {
                $("#recaptchavalue").val(response);
            }
        };
        //gọi Recaptcha lên
        var recaptcha1;
        var recaptcha2;
        var myCallBack = function() {
            //Render the recaptcha1 on the element with ID "recaptchaContact1"
            recaptcha1 = grecaptcha.render('recaptchaContact1', {
                'sitekey': 'Site key của bạn',
                'theme' : 'light'
            });
    
            //Render the recaptcha2 on the element with ID "recaptchaContact1"
            //Gọi callback trả về verifyCallback vì là 2 recaptcha trên 1 webpage, phải trả về và lưu xuống textbox ẩn 1 recaptcha thứ 2, cái đầu xử lý bình thường
            recaptcha2 = grecaptcha.render(document.getElementById('recaptchaContact2'), {
                'sitekey': 'Site key của bạn',
                'callback': verifyCallback,
                'theme': 'light'
            });
        };
    </script>
    
    Bước 4: Tạo 1 Controller để thực hiện các ActionResult được trả từ View
    • Ví dụ ở dưới đây itseovn tạo Controller tên HomeController.cs
    • Controller này để lấy dữ liệu của recaptcha và thực hiện Action bạn muốn.
    Mã:
    using MyNamesPace.Models;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MyNamesPace.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
            [HttpPost]
            public ActionResult Contact1()
            {
                //Recapcha
                CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]);
               if (response.Success == false || ModelState.IsValid == false)
                {
                    ModelState.AddModelError("", "Vui Lòng xác nhận: Tôi không phải là người máy");
                }
                //End Recapcha
    
                return View("Contact");
            }
            [HttpPost]
            public ActionResult Contact2()
            {
                string Recaptcha = Request.Form["recaptchavalue"];
                CaptchaResponse response = ValidateCaptcha(Recaptcha);
                if (response.Success == false || ModelState.IsValid == false)
                {
                    ModelState.AddModelError("", "Vui Lòng xác nhận: Tôi không phải là người máy");
                } 
                return View("Contact");
            }
            public static CaptchaResponse ValidateCaptcha(string response)
            {
                string secret = System.Web.Configuration.WebConfigurationManager.AppSettings["recaptchaPrivateKey"];
                var client = new WebClient();
                var jsonResult = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response));
                return JsonConvert.DeserializeObject<CaptchaResponse>(jsonResult.ToString());
            }
        }
    }
     
    Cảm ơn đã xem bài:

    Add Multiple reCAPTCHA Google in single page C# asp.net MVC

    Chỉnh sửa cuối: 10/10/18


Chủ để tương tự : Multiple reCAPTCHA
Diễn đàn Tiêu đề Date
Lập Trình Website MVC5 & MVC6 Delete Multiple records with Entity Framework Linq ASP.Net MVC 5 20/4/20
Lập Trình Website MVC5 & MVC6 Add Multiple Foreign Key for the Same table in MVC Database First SQL 20/10/18
Lập Trình Website MVC5 & MVC6 Sắp xếp Order By nhiều cột trong LinQ, Order By multiple columns LinQ MVC C# Asp.net 8/8/18