20 secrets of mvc3-(15) Use CAPTCHA to prevent malicious software from automatically submitting comments (Anti-irrigation)

Source: Internet
Author: User

Problem

Some people use automaticProgramSubmitting a form causes a large amount of garbage throughout the internet. One way to prevent this is to use a verification code-CAPTCHA: a fully automated Turing test that distinguishes computers from humans, which forces users to input the generated text into the text box.

CAPTCHA is a more user-friendly verification code. It can distinguish whether post requests are sent by humans or computers through vision and hearing)

Solution

SlaveNugetInstallASP. NET web helpers LibraryIn this way, the bookcommentscontroller can be used to prevent the addition of book reviews.

Discussion

You need to install a new class package to apply CAPTCHA to the form. Microsoft has created an nuget web helpers class containing CAPTCHA, which makes it easy for us to implement and verify CAPTCHA input by users. Open the MVC project and select Tools> librarypackage Manager> Add library package reference in. Click online on the left. You can find the Asp.net web helpers Library at the bottom of the first page. Click Install.

In our example. Software that automatically sends POST requests is generally used in book reviews. So it is the perfect place to add CAPTCHA. Before starting, you must register your domain name at reCAPTCHA website. Generally, a Gmail account is used. We use an existing project or register another one. Here, because our project is used for practice on the local machine, I will register it for my localhost ). After successful registration, you can get a public key and a private key ).

Prompt: If you do not use ajax to include CAPTCHA, you can use the following two lines:CodeChange your view:

 
@ Using Microsoft. Web. helpers;
@ ReCAPTCHA. gethtml ("<Your public key>","<Your private key>")

 

Once the configuration is complete, it is time to update our code. We need to make some small changes in bookcomments/index view. This view was created in the previous section and used to submit book reviews using Ajax. This Ajax should be updated: 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 ";
}
< H2 >
Index </ H2 >
< 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, update bookcomments/create view. First, add a location to display CAPTCHA. Then add a new HTML error message. When they enter an incorrect verification code, an error is prompted. Finally, in the reloadcomment JavaScript function, change the code to not automatically reload the Book Review (only when it is correct ).

@ Model mvcapplication. Models. bookcomment
@{
Viewbag. Title = "CREATE ";
}
< H2 >
Create </ H2 >
@ 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/index? Bookid = @ viewbag. bookid " );
}
}
</ 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" >
Are 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 need to update bookcommentscontroller to verify the input CAPTCHA. If the verification is invalid, add the error message to modelstate and view 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)
{
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 my practice, I don't know if the CAPTCHA background style can be customized. If so, it's cool !)

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.