Problem
In a less fortunate situation, people use automated programs to submit forms, causing a lot of rubbish throughout the internet. One way to prevent this is to use a CAPTCHA---CAPTCHA: fully automated to differentiate between computer and human Turing tests, which forces the user to input the generated text into a text box.
(Translator: Captcha is a more humane verification code, can be visually and auditory to distinguish the POST request is issued by humans or computers)
Solution Solutions
Installs the ASP. NET Web Helpers Library from NuGet to prevent it from adding book reviews in Bookcommentscontroller.
Discuss
A new class package needs to be installed to make it possible to apply captcha on the form. Microsoft has created a NuGet Web helpers class containing CAPTCHA, which makes it easy to implement and validate user-entered captcha. Open the MVC project first and select the Tools→librarypackage manager→add Library package Reference in vs. Click Online on the left and you'll find the ASP. NET Web Helpers Library below the first page. Click Install.
In our case. Software that automatically sends post requests is typically used in book reviews. So it's the perfect place to add captcha. Before you start, you must register for your domain name in reCAPTCHA website. (Translator: Usually use a Gmail account.) We use what we have or re-register a, here because our project is used in native practice, I will register for my localhost). After registering successfully you can get a public key and a private key.
Tip : If you don't use Ajax to include CAPTCHA, you can change your view by following two lines of code:
@using Microsoft.Web.Helpers;
@ReCaptcha. gethtml ("< your public key >", "< your private key >")
Once the configuration is complete, it's time to start updating our code. We need to make some minor changes in Bookcomments/index view. This view is created in the previous paragraph and is used to submit book reviews using Ajax. This Ajax needs to be updated to: When the request is complete, call the JavaScript function to display the CAPTCHA button. The code is as follows:
@model ienumerable<mvcapplication.models.bookcomment>
@{
Viewbag.title = "Index";
}
Index<p>
@Ajax. ActionLink ("Create New", "create", new
{
BookId = Viewbag.bookid
},
New Ajaxoptions {Updatetargetid = "addcomment"})
</p>
<div id= "AddComment" >
</div>
<script type= "Text/javascript" src=
"Http://www.google.com/recaptcha/api/js/recaptcha_ajax.js" >
</script>
<script type= "Text/javascript" >
function Displaycaptcha () {
Recaptcha.destroy ();
Recaptcha.create ("6le27cosaaaaak8kqpuigvz3qtdxga9ud9xst4yy", "Captcha", {});//Your Public key
}
</script>
<table>
<tr>
<th>
Comment
</th>
<th>
Created
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html. displayfor (ModelItem = item.comment)
</td>
<td>
@Html. displayfor (ModelItem = Item. Created)
</td>
<td>
@Html. displayfor (ModelItem = Item. Book.title)
</td>
</tr>
}
</table>
Now, go to update bookcomments/create view. First add a place to show captcha. Then add a new HTML error message that will prompt for errors when they enter the wrong captcha. Finally, change the code in the Reloadcomment JavaScript function to not automatically reload the book review (only reload when it's right).
@model MvcApplication.Models.BookComment
@{
Viewbag.title = "Create";
}
Create@section Javascriptandcss {
<script src= "@Url. Content (" ~/scripts/jquery.validate.min.js ")"
Type= "Text/javascript" ></script>
<script src= "
@Url. Content ("~/scripts/jquery.validate.unobtrusive.min.js") "
Type= "Text/javascript" ></script>
}
<script type= "Text/javascript" >
function reloadcomments () {
var reload = "@ViewBag. Refreshcomments";
if (reload = = "False") {
Displaycaptcha ();
} else {
$ ("#Comments"). Load ("/bookcomments/[email protected]");
}
}
</script>
@using (Ajax.beginform (New ajaxoptions
{
Updatetargetid = "AddComment",
OnComplete = "Reloadcomments"
}))
{
@Html. Hidden ("BookId", (int) viewbag.bookid);
@Html. ValidationSummary (True)
<fieldset>
<legend>BookComment</legend>
<div class= "Editor-label" >
@Html. labelfor (model = model.comment)
</div>
<div class= "Editor-field" >
@Html. textareafor (model = model.comment)
@Html. validationmessagefor (model = model.comment)
</div>
<div class= "Editor-label" >
Is you human?
</div>
<div class= "Editor-field" >
<div id= "Captcha" >
</div>
@Html. Validationmessage ("Captcha")
</div>
<p>
<input type= "Submit" value= "Create"/>
</p>
</fieldset>
}
Finally we want to update Bookcommentscontroller to verify the input captcha. If the validation is not legal, we add the error message to the Modelstate and the view shows it.
Using System;
Using System.Collections.Generic;
Using System.Data;
Using System.Data.Entity;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;
Using Mvcapplication.models;
Using Microsoft.Web.Helpers;
Using Mvcapplication.models;
Namespace Mvcapplication.controllers
{
public class Bookcommentscontroller:controller
{
Private Bookdbcontext db = new Bookdbcontext ();
//
GET:/bookcomments/
Public ActionResult Index (int BookId)
{
Viewbag.bookid = BookId;
var bookcomments = db. Bookcomments.include (
b = b.book). Where (b = b.bookid = = BookId);
Return Partialview (bookcomments. ToList ());
}
//
GET:/bookcomments/create
Public ActionResult Create (int BookId)
{
Viewbag.bookid = BookId;
Viewbag.refreshcomments = false;
return Partialview ();
}
//
POST:/bookcomments/create
[HttpPost]
Public ActionResult Create (bookcomment bookcomment)
{
Viewbag.refreshcomments = false;
var captchasuccess = Recaptcha.validate (
"6le27cosaaaaam6kznxu8m1j9");//Your private key
if (modelstate.isvalid && captchasuccess)
{
Bookcomment. Created = DateTime.Now;
Db. Bookcomments.add (bookcomment);
Db. SaveChanges ();
Viewbag.refreshcomments = true;
}
If CAPTCHA failed add error message
if (!captchasuccess)
{
Modelstate.addmodelerror ("Captcha",
"Invalid CAPTCHA");
}
Viewbag.bookid = bookcomment. BookId;
Return Partialview (bookcomment);
}
protected override void Dispose (bool disposing)
{
Db. Dispose ();
Base. Dispose (disposing);
}
}
}
(Translator: After I practice, I do not know whether this CAPTCHA background style can be customized, if possible, it is too cool!) )
"MVC3" 20 Recipes-(15) use CAPTCHA to prevent malware from automatically submitting comments (anti-drip)