Google Captcha未出现在ASP .NET Core 2.1中

时间:2018-09-06 04:20:34

标签: asp.net recaptcha razor-pages

我目前正在将网站从ASP.NET MVC迁移到ASP.NET Core 2.1 MVC。 除了一件事情,一切都做得很好:contact us表单要求Google Captcha提交消息。

验证码表单没有显示,我不断收到错误消息

  

缺少必需的参数:sitekey

有人可以帮助我吗?我做错什么了吗?还是我错过了一些步骤?

这是我的视图,其中包含预期的验证码

<div class="row">
  <div class="recaptcha">
    <div class="g-recaptcha" data-sitekey="@Model.Captcha"></div>
      <p class="field-validation-error">
        @ViewData["CaptchaError"]
       </p>
    </div>
  <div class="submit">
    @Html.AntiForgeryToken()
     <button type="submit" class="btn">Submit</button>
   </div>
  </div>

我的后端逻辑

public ContactModel(AppSettings appSettings, ContactService contactService)
{
    this.appSettings = appSettings;
    this.contactService = contactService;
}

public string Name { set; get; }
public string Subject { set; get; }
public string Message { set; get; }

public string Captcha { set; get; }

public void OnGet()
{
     Captcha = appSettings.CaptchaPublicKey;
}

[ValidateAntiForgeryToken]
public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    var captchaSuccess = await contactService.ValidateCaptcha(Request.Form["g-recaptcha-response"]);

    if (!captchaSuccess)
    {
        ViewData["CaptchaError"] = "Failed to verify reCAPTCHA response!";
        return Page();
    }

    await contactService.SendMail(Name, Subject, Message);

    TempData["ContactSuccess"] = "Your message has been submitted, thank you! Our customer service will respond to you shortly.";
    return Page();
}

我的appsetting.json

{
  "Logging": {
    "LogLevel": {
    "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ContactInbox": "xxxx",
  "CaptchaPublicKey": "xxxx",
  "CaptchaSecretKey": "xx",
  "SendGridApiKey": "xxx",
  "LoungeInviteUrl": "xxx"
}

这是我如何为模型设置appsetting值

services.Configure<AppSettings>(this.Configuration);
        services.AddTransient(di => di.GetService<IOptions<AppSettings>>().Value);
        services.AddTransient<ContactService>();
        services.AddSingleton(di =>
        {
            var client = new HttpClient();
            // http://byterot.blogspot.co.id/2016/07/singleton-httpclient-dns.html
            client.DefaultRequestHeaders.ConnectionClose = true;
            return client;
        });

最后是我的包含appsetting.json值的模型

public class AppSettings
{
    public string ContactInbox { set; get; }
    public string CaptchaPublicKey { set; get; }
    public string CaptchaSecretKey { set; get; }
    public string SendGridApiKey { set; get; }
    public string LoungeInviteUrl { set; get; }
}

这就是我使用Google验证码所做的。难道我做错了什么?还是错过了一步?请帮助我

非常感谢

编辑: 我尝试将网站密钥硬编码到html中,并且可以正常工作 所以真正的问题是,为什么我的appsetting.json值不会分配给我的模型?

0 个答案:

没有答案