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
-Attribut auf eine Aktion an. Configurations
definieren zulässige Konfigurationen für eine Aktion. Wenn keine angegeben ist, können Sie eine beliebige Konfiguration verwenden. Wenn nur eines angegeben ist, können Sie das Konfigurationstoken weglassen.
AllowedAction
funktioniert mit V2 oder V3. Geben Sie nicht an, dass die Aktionsprüfung übersprungen werden soll.
MinimumScore
funktioniert mit V3. Der Standardwert ist 0.5
.
UseModelErrors
bestimmt, ob Fehler zum MVC-Modell hinzugefügt werden. Standardmäßig wahr.
Sie können eine Recaptcha-Antwort an eine Aktion übergeben, indem Sie FromRecaptchaResponseAttribute
mit einem beliebigen Methodenparameter verwenden, der von IRecaptchaResponse
abgeleitet ist.
[ HttpPost ]
[ AllowAnonymous ]
[ ValidateRecaptcha ( Configurations = new [ ] { "Sitekey1" , "Sitekey2" } , MinimumScore = 0.7 , AllowedAction = "register" ) ]
public async Task < ActionResult > ProtectedByV3AndV2 ( [ FromRecaptchaResponse ] RecaptchaResponse response )
{
// Your Code
}
Die Antwort eines reCAPTCHA sollte in einem HTTP-Header mit dem angegebenen Schlüssel oder g-recaptcha-response
übergeben werden.
Der Konfigurationsschlüssel eines reCAPTCHA sollte in einem HTTP-Header mit dem angegebenen Schlüssel oder g-recaptcha-type
übergeben werden, wenn mehr als eine Konfiguration im Speicher oder in Configurations
angegeben ist.
Wenn das vom Client übergebene Token ungültig ist, werden Modellfehler zu ModelState
hinzugefügt. Siehe RecaptchaErrorCodes
, ValidateRecaptchaAttribute.ErrorCodes
und offizielle Dokumente
MIT