logo

Thông báo

Icon
Error

Chia sẻ
Tùy chọn
Xem
Xem bài viết cuối
Offline admin  
#1 Đã gửi : 16/11/2015 lúc 08:47:16(UTC)
admin

Danh hiệu: Administration

Chức danh:

Nhóm: Administrators
Gia nhập: 23-07-2013(UTC)
Bài viết: 6,094
Man
Viet Nam
Đến từ: Vietnam

Cảm ơn: 10 lần
Được cảm ơn: 2 lần trong 2 bài viết
In this article I will explain with an example, how to validate (check) Google RECaptcha version 2.0 before Form Submit using JavaScript and jQuery in ASP.Net.
The Google RECaptcha version 2.0 allows to validate the Captcha response on client side using its Callback functions.
 
Get Google RECaptcha Site key and Secret key
You need to refer the following article for information on how to get Google RECaptcha Site key and Secret key.
 
HTML Markup
The following HTML Markup consists of an HTML DIV for displaying the Google RECaptcha, a RequiredFieldValidator and a Button control.
There’s also a hidden TextBox txtCaptcha which is used for Google RECaptcha validation.
<div id="dvCaptcha">
</div>
<asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />
<asp:RequiredFieldValidator ID = "rfvCaptcha" ErrorMessage="Captcha validation is required." ControlToValidate="txtCaptcha"
    runat="server" ForeColor = "Red" Display = "Dynamic" />
<br />
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" />
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Net;
using System.Web.Services;
 
WebMethod for RECaptcha Verification
In the code behind, there are two protected string variables which will hold the values of the Google RECaptcha Site key and Secret key.
You need to set the Google RECaptcha Site key and Secret key in their respective variables.
There’s also a WebMethod which will be executed after user answers the Captcha correctly, this WebMethod accepts the response value which will be passed to the Google RECaptcha SiteVerify API along with the secret key and the API will return a JSON response which is sent to the Client Side script for further processing.
C#
public partial class _Default : System.Web.UI.Page
{
    protected static string ReCaptcha_Key = "<RECaptcha Site Key>";
    protected static string ReCaptcha_Secret = "<RECaptcha Secret Key>";
 
    [WebMethod]
    public static string VerifyCaptcha(string response)
    {
        string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + ReCaptcha_Secret + "&response=" + response;
        return (new WebClient()).DownloadString(url);
    }
}
 
RECaptcha Client Side Implementation and Validation
Inside the OnLoadCallBack event handler of the Google RECaptcha API, the RECaptcha is rendered on the page using the render function which accepts the ID of the HTML DIV (within which the RECaptcha will be rendered), the Google RECaptcha Site key and the Callback event handler.
The Callback event is triggered when the user answers the Captcha correctly. The Callback event handler accepts the Captcha response (which is an encoded string value).
The Captcha response value is sent to the WebMethod VerifyCatpcha (discussed earlier) and returns a JSON object containing Success status and some error codes.
If the Success status is true then the value is set in the hidden TextBox and the RequiredFieldValidator is hidden.
If the Success status is false then the RequiredFieldValidator is shown and it is made to display the error message returned from the Google RECaptcha SiteVerify API.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer></script>
<script type="text/javascript">
var onloadCallback = function () {
    grecaptcha.render('dvCaptcha', {
        'sitekey''<%=ReCaptcha_Key %>',
        'callback'function (response) {
            $.ajax({
                type: "POST",
                url: "Default.aspx/VerifyCaptcha",
                data: "{response: '" + response + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var captchaResponse = jQuery.parseJSON(r.d);
                    if (captchaResponse.success) {
                        $("[id*=txtCaptcha]").val(captchaResponse.success);
                        $("[id*=rfvCaptcha]").hide();
                    } else {
                        $("[id*=txtCaptcha]").val("");
                        $("[id*=rfvCaptcha]").show();
                        var error = captchaResponse["error-codes"][0];
                        $("[id*=rfvCaptcha]").html("RECaptcha error. " + error);
                    }
                }
            });
        }
    });
};
</script>
 

Screentshots

Google RECaptcha implemented in ASP.Net

RequiredFieldValidator error message when Captcha is not answered

Google RECaptcha answered correctly

Google RECaptcha error message shown on incorrect answer

Error message shown Google RECaptcha SiteVerify API Success status is False

Source : aspsnippets.com

Ai đang xem chủ đề này?
OceanSpiders 2.0
Di chuyển  
Bạn không thể tạo chủ đề mới trong diễn đàn này.
Bạn không thể trả lời chủ đề trong diễn đàn này.
Bạn không thể xóa bài của bạn trong diễn đàn này.
Bạn không thể sửa bài của bạn trong diễn đàn này.
Bạn không thể tạo bình chọn trong diễn đàn này.
Bạn không thể bỏ phiếu bình chọn trong diễn đàn này.

| Cung cấp bởi YAF.NET 2.2.4.14 | YAF.NET © 2003-2019, Yet Another Forum.NET
Thời gian xử lý trang này hết 0.751 giây.