I have the following .Net framework code:
public static ReCaptchaResponse VerifyCaptcha(string secret, string response)
{
ReCaptchaResponse res = new ReCaptchaResponse();
res.success = false;
if (HttpContext.Current.Request != null)
{
using (System.Net.Http.HttpClient hc = new System.Net.Http.HttpClient())
{
var values = new Dictionary<string,
string> {
{
"secret",
secret
},
{
"response",
response
}
};
var content = new System.Net.Http.FormUrlEncodedContent(values);
var Response = hc.PostAsync("https://www.google.com/recaptcha/api/siteverify", content).Result;
var responseString = Response.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrWhiteSpace(responseString))
{
res = JsonConvert.DeserializeObject<ReCaptchaResponse>(responseString);
return res;
}
else
return res;
}
}
else
return res;
}
I tried to move it to .Net core, so now I have:
public ReCaptchaResponse VerifyReCaptcha(string secret, string response)
{
if (string.IsNullOrWhiteSpace(secret) || string.IsNullOrWhiteSpace(response))
{
throw new ArgumentException("Secret and response are required.");
}
var reCaptchaResponse = new ReCaptchaResponse { Success = false };
try
{
var values = new Dictionary<string, string>
{
{ "secret", secret },
{ "response", response }
};
var content = new FormUrlEncodedContent(values);
// Ensure the Content-Type is set properly
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
// Make the HTTP POST call synchronously
using (var httpClient = new HttpClient())
{
var httpResponse = httpClient.PostAsync("https://www.google.com/recaptcha/api/siteverify", content).Result;
if (httpResponse.IsSuccessStatusCode)
{
var responseString = httpResponse.Content.ReadAsStringAsync().Result;
reCaptchaResponse = JsonConvert.DeserializeObject<ReCaptchaResponse>(responseString);
}
else
{
Console.WriteLine($"Google reCAPTCHA returned {httpResponse.StatusCode}: {httpResponse.ReasonPhrase}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error during reCAPTCHA verification: {ex.Message}");
}
return reCaptchaResponse;
}
The first function works normally, and the captcha is being validated, while the other returns "invalid input response.".
I double checked the secret key and the g-captcha response, and I am sure they are correct.
What could be the issue?
I am thinking of something built-in in .NET core that altering the request?