ASP.NET MVC 微信公共平臺開發 數組
驗證消息的真實性 服務器
public override void OnActionExecuting(ActionExecutingContext filterContext)方法微信
注:服務器接收消息時,再也不是signature而是msg_signatureide
微信服務器推送消息到服務器的HTTP請求報文示例 post
POST /cgi-bin/wxpush? msg_signature=477715d11cdb4164915debcba66cb864d751f3e6×tamp=1409659813&nonce=1372623149 HTTP/1.1加密
Host: qy.weixin.qq.comspa
調用微信接入時驗證的方法,不過參數須要小改動一下,採用新建的數據模型 日誌
1 /// <summary> 2 /// 微信推送消息模型 3 /// </summary> 4 public class WeChatMsgRequestModel 5 { 6 public string timestamp { get; set; } 7 public string nonce { get; set; } 8 9 public string msg_signature { get; set; } 10 }
1 public class WeChatRequestValidAttribute : ActionFilterAttribute 2 { 3 private const string Token = "StupidMe"; 4 5 public override void OnActionExecuting(ActionExecutingContext filterContext) 6 { 7 //參數適配 8 Model.FormatModel.WeChatMsgRequestModel model = new Model.FormatModel.WeChatMsgRequestModel() { nonce= filterContext.HttpContext.Request.QueryString["nonce"],msg_signature= filterContext.HttpContext.Request.QueryString["msg_signature"],timestamp= filterContext.HttpContext.Request.QueryString["timestamp"] }; 9 //驗證 10 if (CheckSignature(model)) 11 { 12 base.OnActionExecuting(filterContext); 13 } 14 } 15 16 private bool CheckSignature(Model.FormatModel.WeChatMsgRequestModel model) 17 { 18 string signature, timestamp, nonce, tempStr; 19 //獲取請求來的參數 20 signature = model.msg_signature; 21 timestamp = model.timestamp; 22 nonce = model.nonce; 23 //建立數組,將 Token, timestamp, nonce 三個參數加入數組 24 string[] array = { Token, timestamp, nonce }; 25 //進行排序 26 Array.Sort(array); 27 //拼接爲一個字符串 28 tempStr = String.Join("", array); 29 //對字符串進行 SHA1加密 30 tempStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tempStr, "SHA1").ToLower(); 31 //判斷signature 是否正確 32 if (tempStr.Equals(signature)) 33 { 34 return true; 35 } 36 else 37 { 38 return false; 39 } 40 } 41 }
1 2 /// <summary> 3 /// 日誌助手 4 /// </summary> 5 private static Common.LogHelper logger = new Common.LogHelper(typeof(HomeController)); 6 7 [Filters.WeChatRequestValid] 8 public void Valid(Model.FormatModel.WeChatMsgRequestModel model) 9 { 10 if (ModelState.IsValid) 11 { 12 try 13 { 14 //判斷是不是POST請求 15 if (HttpContext.Request.HttpMethod.ToUpper() == "POST") 16 { 17 //從請求的數據流中獲取請求信息 18 using (Stream stream = HttpContext.Request.InputStream) 19 { 20 byte[] postBytes = new byte[stream.Length]; 21 stream.Read(postBytes, 0, (int)stream.Length); 22 string postString = System.Text.Encoding.UTF8.GetString(postBytes); 23 Handle(postString,model); 24 } 25 } 26 } 27 catch (Exception ex) 28 { 29 logger.Error("發生異常,異常信息:" + ex.Message + ex.StackTrace); 30 } 31 } 32 }