Nuget
Install-Package Spaier.Recaptcha
.NET CLI
dotnet add package Spaier.Recaptcha
public void ConfigureServices ( IServiceCollection services ) {
// Your Code
services . AddRecaptcha ( )
// Use appsettings.json
//.AddInMemoryConfigurationStore(Configuration.GetSection("Recaptcha"))
. AddInMemoryConfigurationStore ( new Dictionary < string , RecaptchaConfiguration >
{
[ "Sitekey1" ] = new RecaptchaConfiguration ( RecaptchaDefaults . TestSecretKey , RecaptchaSecretType . V2 ) ,
[ "Sitekey2" ] = new RecaptchaConfiguration ( RecaptchaDefaults . TestSecretKey , RecaptchaSecretType . V2Android ) ,
[ "Sitekey3" ] = new RecaptchaConfiguration ( RecaptchaDefaults . TestSecretKey , RecaptchaSecretType . V3 ) ,
} )
. AddTokenHeaderProvider ( )
. AddConfigurationHeaderProvider ( )
. AddRecaptchaHttpClient ( configureHttpBuilder : httpBuilder =>
{
// You can setup Polly here
httpBuilder . AddTransientHttpErrorPolicy ( builder => builder . WaitAndRetryAsync ( new [ ]
{
TimeSpan . FromSeconds ( 1 ) ,
TimeSpan . FromSeconds ( 5 ) ,
TimeSpan . FromSeconds ( 10 )
} ) ) ;
} )
. UseGoogleUrl ( ) ;
// UseGlobalUrl(); // will use recaptcha.net mirror. Useful for countries where google.com is blocked.
// UseCustomUrl("your_url"); // will use custom url for validation.
}
ValidateRecaptcha
ke suatu tindakan. Configurations
mendefinisikan konfigurasi yang diizinkan untuk suatu tindakan. Jika tidak ada yang ditentukan, Anda dapat menggunakan konfigurasi apa pun. Jika hanya satu yang ditentukan, Anda dapat menghilangkan token konfigurasi.
AllowedAction
berfungsi dengan V2 atau V3. Jangan tentukan untuk melewati pemeriksaan tindakan.
MinimumScore
berfungsi dengan V3. Defaultnya adalah 0.5
.
UseModelErrors
menentukan apakah kesalahan akan ditambahkan ke Model MVC. Benar secara default.
Anda dapat meneruskan respons recaptcha ke suatu tindakan dengan menggunakan FromRecaptchaResponseAttribute
dengan parameter metode apa pun yang berasal dari IRecaptchaResponse
.
[ HttpPost ]
[ AllowAnonymous ]
[ ValidateRecaptcha ( Configurations = new [ ] { "Sitekey1" , "Sitekey2" } , MinimumScore = 0.7 , AllowedAction = "register" ) ]
public async Task < ActionResult > ProtectedByV3AndV2 ( [ FromRecaptchaResponse ] RecaptchaResponse response )
{
// Your Code
}
Respons reCAPTCHA harus diteruskan dalam header HTTP dengan kunci yang ditentukan atau g-recaptcha-response
.
Kunci konfigurasi reCAPTCHA harus diteruskan dalam header HTTP dengan kunci yang ditentukan atau g-recaptcha-type
jika ada lebih dari satu konfigurasi yang disimpan atau ditentukan dalam Configurations
.
Jika token yang diteruskan oleh sisi klien tidak valid, kesalahan model akan ditambahkan ke ModelState
. Lihat RecaptchaErrorCodes
, ValidateRecaptchaAttribute.ErrorCodes
dan dokumen resmi
MIT