Tuesday, 10 November 2020

Google Captcha for C# ASP.Net MVC

 

reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep malicious software from engaging in abusive activities on your website. Meanwhile, legitimate users will be able to login, make purchases, view pages, or create accounts and fake users will be blocked.

VIEW Code

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

<form method="post" class="comment-form">

    @Html.AntiForgeryToken()

    <div class="row">

        <div class="col-lg-6">

            <input type="text" name="Name" placeholder="Name" required>

        </div>

        <div class="col-lg-6">

            <input type="text" name="Phone" pattern="[0-9]{10}" title="Name (MAX-10 characters only)" placeholder="Phone" required>

        </div>

        <div class="col-lg-12">

            <input type="email" name="Email" placeholder="Email">

        </div>

        <div class="col-lg-12">

            <textarea name="Message" placeholder="Message" required></textarea>

        </div>

        <div class="col-lg-12">

            <div class="g-recaptcha" data-sitekey="your public key"></div><br />

            <input type="submit" name="Submit" class="btn" value="Send Message" style="background-color: #ed3237;color:black" />

        </div>

    </div>

</form>


Controller

using Newtonsoft.Json;

using System.Net;

[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult Contact(ContactModel data)

{

    CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]);

    if (ModelState.IsValid && response.Success)

    {

        InsertRepository ob = new InsertRepository();

        string ErrMsg="";

        if (ob.AddWebsiteMessage(data, ref ErrMsg))

        {                     

            return RedirectToAction("Thanks", "Common", new { msg = "Thanks for contacting us.We will get back to you shortly with a revert on your query" });

               

        }               

        else

            return RedirectToAction("Error", "Common", new { msg = ErrMsg });

    }

    else

    {

        if(response.Success==false)

            return RedirectToAction("Error", "Common", new { msg = "Invalid Captcha" });

        else

            return RedirectToAction("Error", "Common", new { msg = "Bots Attempt" });

    }                          

}


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());

}


Model

public class CaptchaResponse
{ 

    public bool Success { get; set; }
    public List<string> ErrorMessage { get; set; }

}

Web.config

<appSettings>

    <add key="recaptchaPublickey" value="your public key"/>

    <add key="recaptchaPrivatekey" value="your private key"/>

  </appSettings>

                        

Next Topic

No comments:

Post a Comment