20 tips for ASP. net mvc 3 Development (15th) [20 recipes for programming MVC 3]: Enable CAPTCHA)

Source: Internet
Author: User

Topics

Many automatedProgramThe form is automatically submitted, causing a large amount of junk data on the Internet. To prevent this situation, we have implemented a graphic Verification Code (CAPTCHA:Completely automated public Turing test to tell computers and humans
Apart), You must enter the correct characters displayed on the image in the text box when submitting the request.

 

Solution

InBookcommentscontrollorController InstallationASP. NET web helper LibraryMediumNugetProvidedCAPTCHA.

 

Discussion

Contains a newLibrary package, AddCAPTCHA.MicrosoftInNuget Web
Helpers LibraryBuilt-inCAPTCHAClass, so that we can easily verify the user inputCAPTCHA.

 

InVisual StudioOfMVCIn the Application project, click "Tools">"Library Package Manager"→"Add Library
Package reference". After loading, select"Online"Category, select"Microsoft-web-helpers", If it is not in the list, search in the upper right corner. Click"Install".

 

The most typical case of submitting a form is submitting a comment. In the previous formula, adding a book comment is to addCAPTCHA. Before starting, You need to register the domain nameReCAPTCHAWebsite. After registration, you will receive the private key and public key for your website. Copy and save them for future use.

 

Modify the settingsCode. InBookcomments/IndexMake a small modification to the view. This is the previously created page for adding comments.AjaxRequest, displayedCAPTCHAWhen the request is complete,Displaycaptcha"JavascriptMethod.

@ Model ienumerable <  Mvcapplication4  . Models. bookcomment  > 
@{
Viewbag. Title = "Index ";
}
< H2 > Index </ H2 >
< P >
@ Ajax. actionlink ("create new", "CREATE", new {
Bookid = viewbag. bookid },
New ajaxoptions {updatetargetid = "addcomment ",
Oncomplete = "displaycaptcha "})
</ 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 ( " <Your_public_key> " , " CAPTCHA " ,{});
}

</ Script >

NowBookcomments/createMake a small modification to the view. First, you need to create a region displayCAPTCHAAnd a newHtmlMark, the error message is displayed when the user inputs an error. Finally, modifyReloadcommentMethod to displayCAPTCHA(Only when no error occurs ).

@ Model mvcapplication4.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, you need to modifyBookCommentscontrollerVerify user inputCAPTCHA. If the verification fails, add the error messageModelstateIs returned to the view.

 Using System;
Using System. Collections. Generic;
Using System. Data;
Using System. Data. entity;
Using System. LINQ;
Using System. Web;
Using System. Web. MVC;
Using Mvcapplication4.models;
Using Microsoft. Web. helpers;

Namespace Mvcapplication4.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 (
" <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 );
}
}
}

Reference

Original book addressBooksSource code

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.