前言
C# 是一個現(xiàn)代的逸月、通用的瘦穆、面向?qū)ο蟮木幊陶Z言纪隙,它是由微軟(Microsoft)開發(fā)的,由 Ecma 和 ISO 核準認可的扛或。突發(fā)奇想绵咱,動手開發(fā)一個C#滑動拼圖驗證碼,下面是我開發(fā)過程的記錄熙兔。
準備工作
本文使用IIS搭建環(huán)境沧卢,同時確保項目運行正常冀泻。
目錄結(jié)構(gòu)
核心代碼
- noramal.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>凱格行為驗證碼 - Net C# demo</title>
<link rel="stylesheet" href="./style/demo.css" />
<!--
將以下域名替換成你的“應(yīng)用服務(wù)器域名”
將以下 appid 替換成你的 AppID
服務(wù)器域名和appid在你的應(yīng)用管理中獲取
示例:<script src="captcha.js?appid=xxx"></script>
-->
<script src="captcha.js?appid=appId"></script>
<script>
kg.captcha({
// 綁定顯示區(qū)域
bind: "#captchaBox",
// 驗證成功事務(wù)處理
success: function (e) {
console.log(e);
// 將驗證成功后的 token 通過隱藏域傳遞到后端
kg.$("#kgCaptchaToken").value = e["token"];
},
// 驗證失敗事務(wù)處理
failure: function (e) {
console.log(e);
},
// 點擊刷新按鈕時觸發(fā)
refresh: function (e) {
console.log(e);
}
});
// 檢查表單提交
function check() {
if (kg.$("#kgCaptchaToken").value == "") {
alert("請完成圖形驗證后提交")
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<form action="demo.aspx?cty=1" method="post" id="form" onsubmit="return check();">
<!-- 將驗證成功后的 token 通過隱藏域傳遞到后端 -->
<input type="hidden" name="kgCaptchaToken" id="kgCaptchaToken" value="" />
<div class="inputForm">
<input type="text" name="username" placeholder=" 例:填寫登錄帳號" />
<br/>
<input type="password" name="password" placeholder=" 例:填寫登錄密碼" />
</div>
<!-- 綁定顯示區(qū)域 -->
<div id="captchaBox"></div>
<input type="submit" value="提 交" class="btn" />
</form>
</body>
</html>
- demo.aspx.cs
using System;
using KgCaptchaSDK;
public partial class _Default : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e) {
// 后端處理
string html, appId, appSecret, Token;
if (Request.Form.ToString().Length > 0){ // 有數(shù)據(jù)處理
string cty = Request.QueryString["cty"];
// 設(shè)置 AppId 及 AppSecret约郁,在應(yīng)用管理中獲取
if (cty == "1"){
appId = "appId";
appSecret = "appSecret";
}
// 填寫你的 AppId 和 AppSecret信柿,在應(yīng)用管理中獲取
var request = new kgCaptcha(appId, appSecret);
// 前端驗證成功后頒發(fā)的 token,有效期為兩分鐘
request.token = Request.Form["kgCaptchaToken"];
// 填寫應(yīng)用服務(wù)域名舆声,在應(yīng)用管理中獲取
request.appCdn = "https://cdn.kgcaptcha.com";
// 當安全策略中的防控等級為3時必須填寫花沉,一般情況下可以忽略
// 可以填寫用戶輸入的登錄帳號(如:$_POST["username"])柳爽,可攔截同一帳號多次嘗試等行為
request.userId = "kgCaptchaDemo";
// 請求超時時間,秒
request.connectTimeout = 5;
// 發(fā)送驗證請求
var requestResult = request.sendRequest();
if (requestResult.code == 0) {
// 驗簽成功邏輯處理 ***
// 這里做驗證通過后的數(shù)據(jù)處理
// 如登錄/注冊場景碱屁,這里通常查詢數(shù)據(jù)庫磷脯、校驗密碼、進行登錄或注冊等動作處理
// 如短信場景娩脾,這里可以開始向用戶發(fā)送短信等動作處理
// ...
html = "<script>alert('驗證通過');history.back();</script>";
} else {
// 驗簽失敗邏輯處理
html = "<script>alert(\"" + requestResult.msg + " - " + requestResult.code + "\");history.back();</script>";
}
// 輸出結(jié)果
Response.Write(html);
} else {
Response.Redirect("index.html");
}
}
}
效果展示
最后
SDK開源地址:https://github.com/KgCaptcha赵誓,順便做了一個演示:https://www.kgcaptcha.com/demo/