ASP.NET MVC 微信公共平台开发
验证消息的真实性
-
在MVC Controller所在项目中添加过滤器,在过滤器中重写
public override void OnActionExecuting(ActionExecutingContext filterContext)方法
-
新建数据模型
注:服务器接收消息时,不再是signature而是msg_signature
-
方法重写,实现对消息的验证
调用微信接入时验证的方法,不过参数需要小改动一下,采用新建的数据模型
-
在Action方法或在Controller上添加过滤器属性
- 代码示例
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 }