1 [Route("wechat")]
2 [HttpGet]
3 public ActionResult WechatValidation(string echoStr,string signature,string timestamp,string nonce)
4 {
5 string filename = "1.text";
6 string webRootPath = _hostingEnvironment.WebRootPath;
7 string contentRootPath = _hostingEnvironment.ContentRootPath;
8 string fullpath = Path.Combine(webRootPath, filename);
9 if (!System.IO.File.Exists(fullpath))
10 {
11 System.IO.File.Create(fullpath).Close();
12 }
13
14 System.IO.File.AppendAllText(fullpath, $"\r\nTime:{DateTime.Now},string echoStr:{echoStr},string signature:{signature},string timestamp:{timestamp},string nonce:{nonce}");
15
16 var token = "wechat";
17 var checkResult = CheckSignature(token, signature, timestamp, nonce);
18 return Content(echoStr);
19 }
20
21
22 private bool CheckSignature(string token, string signature, string timestamp, string nonce)
23 {
24
25 //创建数组,将 Token, timestamp, nonce 三个参数加入数组
26 string[] array = { token, timestamp, nonce };
27 //进行排序
28 Array.Sort(array);
29 //拼接为一个字符串
30 var tempStr = String.Join("", array);
31 //对字符串进行 SHA1加密
32 tempStr = Get_SHA1_Method2(tempStr);
33 //判断signature 是否正确
34 if (tempStr.Equals(signature))
35 {
36 return true;
37 }
38 else
39 {
40 return false;
41 }
42 }
43
44 public string Get_SHA1_Method2(string strSource)
45 {
46 string strResult = "";
47
48 //Create
49 System.Security.Cryptography.SHA1 md5 = System.Security.Cryptography.SHA1.Create();
50
51 //注意编码UTF8、UTF7、Unicode等的选择
52 byte[] bytResult = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strSource));
53
54 //字节类型的数组转换为字符串
55 for (int i = 0; i < bytResult.Length; i++)
56 {
57 //16进制转换
58 strResult = strResult + bytResult.ToString("X");
59 }
60 return strResult.ToLower();
61 }