篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html 谷歌reCAPTCHA ASP.NET C#,ASP.NET Web API相关的知识,希望对你有一定的参考价值。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace Net
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// add client side domain here
var cors = new EnableCorsAttribute("http://localhost:3360 , http://localhost:58059, http://localhost:3305", "*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "v1/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace Net.Models.ViewModel.GoogleReCaptcha
{
public class ReCaptchaViewModel
{
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("challenge_ts")]
public DateTime Challenge { get; set; }
[JsonProperty("hostname")]
public string Hostname { get; set; }
}
}
using System;
using System.Configuration;
using System.Net;
using System.Web;
using System.Web.Http;
using Net.Models.ViewModel.GoogleReCaptcha;
using Newtonsoft.Json;
namespace Net.Controllers.Education.GoogleReCaptcha
{
[RoutePrefix("v1/captcha")]
public class ReCaptchaController : ApiController
{
ReCaptchaViewModel result = new ReCaptchaViewModel();
string value = string.Empty;
string secret = string.Empty;
string url = string.Empty;
public ReCaptchaController()
{
secret = ConfigurationManager.AppSettings["SecretKey"].ToString();
}
[HttpPost]
[Route("validuser")]
public IHttpActionResult ValidUser()
{
try
{
foreach (string key in HttpContext.Current.Request.Form.AllKeys)
value = HttpContext.Current.Request.Form["g-recaptcha-response"];
if (string.IsNullOrEmpty(value))
return BadRequest("User Token key missing");
var client = new WebClient();
url = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, value);
var response = client.DownloadString(url);
result = JsonConvert.DeserializeObject<ReCaptchaViewModel>(response);
if (result.Success == true)
{
//Success
}
else
{
//error
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
return Ok();
}
}
}