private string Token = ConfigurationManager.AppSettings["Token"];
[HttpGet]
[ActionName("Index")]
public ActionResult Get(string signature, string timestamp, string nonce, string echostr)
{
if (CheckSignature.Check(signature, timestamp, nonce, Token))
{
return Content(echostr);//返回随机字符串则表示验证通过
}
else
{
return Content("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token) + "。如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。");
}
}
///
/// 检查签名是否正确
///
///
///
///
///
///
public static bool Check(string signature, string timestamp, string nonce, string token = null)
{
return signature == GetSignature(timestamp, nonce, token);
}
///
/// 返回正确的签名
///
///
///
///
///
public static string GetSignature(string timestamp, string nonce, string token = null)
{
token = token ?? Token;
var arr = new[] { token, timestamp, nonce }.OrderBy(z => z).ToArray();
var arrString = string.Join("", arr);
//var enText = FormsAuthentication.HashPasswordForStoringInConfigFile(arrString, "SHA1");//使用System.Web.Security程序集
var sha1 = System.Security.Cryptography.SHA1.Create();
var sha1Arr = sha1.ComputeHash(Encoding.UTF8.GetBytes(arrString));
StringBuilder enText = new StringBuilder();
foreach (var b in sha1Arr)
{
enText.AppendFormat("{0:x2}", b);
}
return enText.ToString();
}