public ActionResult Post(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { return(Content("参数错误!")); } postModel.Token = Token; //根据自己后台的设置保持一致 postModel.EncodingAESKey = EncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = WxOpenAppId; //根据自己后台的设置保持一致(必须提供) //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 var maxRecordCount = 10; var logPath = ServerUtility.ContentRootMapPath(string.Format("~/App_Data/WxOpen/{0}/", SystemTime.Now.ToString("yyyy-MM-dd"))); if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomWxOpenMessageHandler(Request.GetRequestMemoryStream(), postModel, maxRecordCount); try { /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/ messageHandler.OmitRepeatedMessage = true; //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。 messageHandler.SaveRequestMessageLog(); //记录 Request 日志(可选) messageHandler.Execute(); //执行微信处理过程(关键) messageHandler.SaveResponseMessageLog(); //记录 Response 日志(可选) //return Content(messageHandler.ResponseDocument.ToString());//v0.7- return(new FixWeixinBugWeixinResult(messageHandler)); //为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 //return new WeixinResult(messageHandler);//v0.8+ } catch (Exception ex) { using (TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Error_WxOpen_" + _getRandomFileName() + ".txt"))) { tw.WriteLine("ExecptionMessage:" + ex.Message); tw.WriteLine(ex.Source); tw.WriteLine(ex.StackTrace); //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } if (ex.InnerException != null) { tw.WriteLine("========= InnerException ========="); tw.WriteLine(ex.InnerException.Message); tw.WriteLine(ex.InnerException.Source); tw.WriteLine(ex.InnerException.StackTrace); } tw.Flush(); tw.Close(); } return(Content("")); } }
public ActionResult Post(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, WxPayConfig.TOKEN)) { return(Content("参数错误!")); } postModel.Token = Token; postModel.EncodingAESKey = EncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = AppId; //根据自己后台的设置保持一致 //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 var maxRecordCount = 10; var logPath = Server.MapPath(string.Format("~/App_Data/MP/{0}/", DateTime.Now.ToString("yyyy-MM-dd"))); if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream, SetWeChat, _container, maxRecordCount); try { //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。 messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}.txt", DateTime.Now.Ticks, messageHandler.RequestMessage.FromUserName))); if (messageHandler.UsingEcryptMessage) { messageHandler.EcryptRequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_Ecrypt_{1}.txt", DateTime.Now.Ticks, messageHandler.RequestMessage.FromUserName))); } /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/ messageHandler.OmitRepeatedMessage = true; //执行微信处理过程 messageHandler.Execute(); //测试时可开启,帮助跟踪数据 if (messageHandler.ResponseDocument == null) { throw new Exception(messageHandler.RequestDocument.ToString()); } if (messageHandler.ResponseDocument != null) { messageHandler.ResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_{1}.txt", DateTime.Now.Ticks, messageHandler.RequestMessage.FromUserName))); } if (messageHandler.UsingEcryptMessage) { //记录加密后的响应信息 messageHandler.FinalResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_Final_{1}.txt", DateTime.Now.Ticks, messageHandler.RequestMessage.FromUserName))); } return(Content(messageHandler.ResponseDocument.ToString()));//v0.7- //return new FixWeixinBugWeixinResult(messageHandler);//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 //return new WeixinResult(messageHandler);//v0.8+ } catch (Exception ex) { using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".txt"))) { tw.WriteLine("ExecptionMessage:" + ex.Message); tw.WriteLine(ex.Source); tw.WriteLine(ex.StackTrace); //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } if (ex.InnerException != null) { tw.WriteLine("========= InnerException ========="); tw.WriteLine(ex.InnerException.Message); tw.WriteLine(ex.InnerException.Source); tw.WriteLine(ex.InnerException.StackTrace); } tw.Flush(); tw.Close(); } return(Content("")); } }
public ActionResult Post(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { return(Content("参数错误!")); } #region 打包 PostModel 信息 postModel.Token = Token; //根据自己后台的设置保持一致 postModel.EncodingAESKey = EncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = AppId; //根据自己后台的设置保持一致 #endregion //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 var maxRecordCount = 10; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount); #region 设置消息去重 /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/ messageHandler.OmitRepeatedMessage = true;//默认已经开启,此处仅作为演示,也可以设置为false在本次请求中停用此功能 #endregion try { messageHandler.SaveRequestMessageLog(); //记录 Request 日志(可选) messageHandler.Execute(); //执行微信处理过程(关键) messageHandler.SaveResponseMessageLog(); //记录 Response 日志(可选) //return Content(messageHandler.ResponseDocument.ToString());//v0.7- //return new WeixinResult(messageHandler);//v0.8+ return(new FixWeixinBugWeixinResult(messageHandler));//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 } catch (Exception ex) { #region 异常处理 WeixinTrace.Log("MessageHandler错误:{0}", ex.Message); using (TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Error_" + _getRandomFileName() + ".txt"))) { tw.WriteLine("ExecptionMessage:" + ex.Message); tw.WriteLine(ex.Source); tw.WriteLine(ex.StackTrace); //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } if (ex.InnerException != null) { tw.WriteLine("========= InnerException ========="); tw.WriteLine(ex.InnerException.Message); tw.WriteLine(ex.InnerException.Source); tw.WriteLine(ex.InnerException.StackTrace); } tw.Flush(); tw.Close(); } return(Content("")); #endregion } }
public void ProcessRequest(HttpContext context) { string signature = Request["signature"]; string timestamp = Request["timestamp"]; string nonce = Request["nonce"]; string echoStr = Request["echostr"]; if (Request.HttpMethod == "GET") { if (CheckSignature.Check(signature, timestamp, nonce, token)) { WriteContent(echoStr); } else { WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, token) + "。" + "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。" + echoStr); } Response.End(); } else { if (!CheckSignature.Check(signature, timestamp, nonce, token)) { WriteContent("参数错误"); Response.End(); } var postModel = new PostModel { Signature = Request.QueryString["signature"], Msg_Signature = Request.QueryString["msg_signature"], Timestamp = Request.QueryString["timestamp"], Nonce = Request.QueryString["nonce"], Token = token, EncodingAESKey = encodingAESKey, AppId = appId }; int maxRecordCount = 10; var messageHandler = new MyCustomHandler(Request.InputStream, postModel, maxRecordCount); try { messageHandler.RequestDocument.Save( HttpContext.Current.Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" + messageHandler.RequestMessage.FromUserName + ".txt")); //执行微信处理过程 messageHandler.Execute(); //测试时可开启,帮助跟踪数据 messageHandler.ResponseDocument.Save( HttpContext.Current.Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" + messageHandler.ResponseMessage.ToUserName + ".txt")); WriteContent(messageHandler.ResponseDocument.ToString()); return; } catch (Exception ex) { WriteContent(ex.Message); } finally { Response.End(); } } }
private readonly string Token = "konglin";//与微信公众账号后台的Token设置保持一致,区分大小写。 protected void Page_Load(object sender, EventArgs e) { string signature = Request["signature"]; string timestamp = Request["timestamp"]; string nonce = Request["nonce"]; string echostr = Request["echostr"]; if (Request.HttpMethod == "GET") { //get method - 仅在微信后台填写URL验证时触发 if (CheckSignature.Check(signature, timestamp, nonce, Token)) { WriteContent(echostr); //返回随机字符串则表示验证通过 } else { WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token) + "。" + "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。"); } Response.End(); } else { //post method - 当有用户想公众账号发送消息时触发 if (!CheckSignature.Check(signature, timestamp, nonce, Token)) { WriteContent("参数错误!"); return; } //post method - 当有用户想公众账号发送消息时触发 var postModel = new PostModel() { Signature = Request.QueryString["signature"], Msg_Signature = Request.QueryString["msg_signature"], Timestamp = Request.QueryString["timestamp"], Nonce = Request.QueryString["nonce"], //以下保密信息不会(不应该)在网络上传播,请注意 Token = Token, EncodingAESKey = "lXUYdfuGlL9bI7uubwWrSILsEY1ixnt20K6TMPtfV36", //根据自己后台的设置保持一致 AppId = "wxd5ce64c5121b6122" //根据自己后台的设置保持一致 }; //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 var maxRecordCount = 10; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount); try { //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。 messageHandler.RequestDocument.Save( Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" + messageHandler.RequestMessage.FromUserName + ".txt")); //执行微信处理过程 messageHandler.Execute(); //测试时可开启,帮助跟踪数据 messageHandler.ResponseDocument.Save( Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" + messageHandler.ResponseMessage.ToUserName + ".txt")); WriteContent(messageHandler.ResponseDocument.ToString()); return; } catch (Exception ex) { using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".txt"))) { tw.WriteLine(ex.Message); tw.WriteLine(ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } tw.Flush(); tw.Close(); } } finally { Response.End(); } } }
public ActionResult OldPost(string signature, string timestamp, string nonce, string echostr) { LocationService locationService = new LocationService(); EventService eventService = new EventService(); if (!CheckSignature.Check(signature, timestamp, nonce, Token)) { return(Content("参数错误!")); } XDocument requestDoc = null; try { requestDoc = XDocument.Load(Request.Body); var requestMessage = RequestMessageFactory.GetRequestEntity(requestDoc); //如果不需要记录requestDoc,只需要: //var requestMessage = RequestMessageFactory.GetRequestEntity(Request.InputStream); requestDoc.Save(ServerUtility.ContentRootMapPath("~/App_Data/" + SystemTime.Now.Ticks + "_Request_" + requestMessage.FromUserName + ".txt"));//测试时可开启,帮助跟踪数据 ResponseMessageBase responseMessage = null; switch (requestMessage.MsgType) { case RequestMsgType.Text: //文字 { //TODO:交给Service处理具体信息,参考/Service/EventSercice.cs 及 /Service/LocationSercice.cs var strongRequestMessage = requestMessage as RequestMessageText; var strongresponseMessage = ResponseMessageBase.CreateFromRequestMessage <ResponseMessageText>(requestMessage); strongresponseMessage.Content = string.Format( "您刚才发送了文字信息:{0}\r\n您还可以发送【位置】【图片】【语音】等类型的信息,查看不同格式的回复。\r\nSDK官方地址:http://sdk.weixin.senparc.com", strongRequestMessage.Content); responseMessage = strongresponseMessage; break; } case RequestMsgType.Location: //位置 { responseMessage = locationService.GetResponseMessage(requestMessage as RequestMessageLocation); break; } case RequestMsgType.Image: //图片 { //TODO:交给Service处理具体信息 var strongRequestMessage = requestMessage as RequestMessageImage; var strongresponseMessage = ResponseMessageBase.CreateFromRequestMessage <ResponseMessageNews>(requestMessage); strongresponseMessage.Articles.Add(new Article() { Title = "您刚才发送了图片信息", Description = "您发送的图片将会显示在边上", PicUrl = strongRequestMessage.PicUrl, Url = "http://sdk.weixin.senparc.com" }); strongresponseMessage.Articles.Add(new Article() { Title = "第二条", Description = "第二条带连接的内容", PicUrl = strongRequestMessage.PicUrl, Url = "http://sdk.weixin.senparc.com" }); responseMessage = strongresponseMessage; break; } case RequestMsgType.Voice: //语音 { //TODO:交给Service处理具体信息 var strongRequestMessage = requestMessage as RequestMessageVoice; var strongresponseMessage = ResponseMessageBase.CreateFromRequestMessage <ResponseMessageMusic>(requestMessage); strongresponseMessage.Music.MusicUrl = "http://sdk.weixin.senparc.com/Content/music1.mp3"; responseMessage = strongresponseMessage; break; } case RequestMsgType.Event: //事件 { responseMessage = eventService.GetResponseMessage(requestMessage as RequestMessageEventBase); break; } default: throw new ArgumentOutOfRangeException(); } var responseDoc = Senparc.NeuChar.Helpers.EntityHelper.ConvertEntityToXml(responseMessage); responseDoc.Save(ServerUtility.ContentRootMapPath("~/App_Data/" + SystemTime.Now.Ticks + "_Response_" + responseMessage.ToUserName + ".txt"));//测试时可开启,帮助跟踪数据 return(Content(responseDoc.ToString())); //如果不需要记录responseDoc,只需要: //return Content(responseMessage.ConvertEntityToXmlString()); } catch (Exception ex) { using ( TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Error_" + SystemTime.Now.Ticks + ".txt"))) { tw.WriteLine(ex.Message); tw.WriteLine(ex.InnerException.Message); if (requestDoc != null) { tw.WriteLine(requestDoc.ToString()); } tw.Flush(); tw.Close(); } return(Content("")); } }
public async Task <ActionResult> PostAsync(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { return(Content("参数错误!")); } #region 打包 PostModel 信息 postModel.Token = Token; //根据自己后台的设置保持一致 postModel.EncodingAESKey = EncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = AppId; //根据自己后台的设置保持一致 #endregion //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 var maxRecordCount = 10; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler.CustomMessageHandler(Request.GetRequestMemoryStream(), postModel, maxRecordCount); #region 设置消息去重 /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/ messageHandler.OmitRepeatedMessage = true;//默认已经开启,此处仅作为演示,也可以设置为false在本次请求中停用此功能 #endregion try { #region 记录 Request 日志 var logPath = Server.GetMapPath(string.Format("~/App_Data/MP/{0}/", DateTime.Now.ToString("yyyy-MM-dd"))); if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。 messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}_{2}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName, messageHandler.RequestMessage.MsgType))); if (messageHandler.UsingEcryptMessage) { messageHandler.EcryptRequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_Ecrypt_{1}_{2}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName, messageHandler.RequestMessage.MsgType))); } #endregion //执行微信处理过程 messageHandler.Execute(); #region 记录 Response 日志 //测试时可开启,帮助跟踪数据 //if (messageHandler.ResponseDocument == null) //{ // throw new Exception(messageHandler.RequestDocument.ToString()); //} if (messageHandler.ResponseDocument != null && messageHandler.ResponseDocument.Root != null) { messageHandler.ResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_{1}_{2}.txt", _getRandomFileName(), messageHandler.ResponseMessage.ToUserName, messageHandler.ResponseMessage.MsgType))); } if (messageHandler.UsingEcryptMessage && messageHandler.FinalResponseDocument != null && messageHandler.FinalResponseDocument.Root != null) { //记录加密后的响应信息 messageHandler.FinalResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_Final_{1}_{2}.txt", _getRandomFileName(), messageHandler.ResponseMessage.ToUserName, messageHandler.ResponseMessage.MsgType))); } #endregion await _weixinInteractionServer.AddInteraction(messageHandler.RequestDocument.ToString(), messageHandler.ResponseDocument.ToString()); //return Content(messageHandler.ResponseDocument.ToString());//v0.7- //return new WeixinResult(messageHandler);//v0.8+ return(new FixWeixinBugWeixinResult(messageHandler));//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 } catch (Exception ex) { #region 异常处理 WeixinTrace.Log("MessageHandler错误:{0}", ex.Message); using (TextWriter tw = new StreamWriter(Server.GetMapPath("~/App_Data/Error_" + _getRandomFileName() + ".txt"))) { tw.WriteLine("ExecptionMessage:" + ex.Message); tw.WriteLine(ex.Source); tw.WriteLine(ex.StackTrace); //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } if (ex.InnerException != null) { tw.WriteLine("========= InnerException ========="); tw.WriteLine(ex.InnerException.Message); tw.WriteLine(ex.InnerException.Source); tw.WriteLine(ex.InnerException.StackTrace); } tw.Flush(); tw.Close(); } return(Content("")); #endregion } }
protected void Page_Load(object sender, EventArgs e) { string signature = Request["signature"]; string timestamp = Request["timestamp"]; string nonce = Request["nonce"]; string echostr = Request["echostr"]; if (Request.HttpMethod == "POST") { //post method if (!CheckSignature.Check(signature, timestamp, nonce, Token)) { Content("参数错误!"); return; } //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream); try { //测试时可开启此记录,帮助跟踪数据 messageHandler.RequestDocument.Save(Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" + messageHandler.RequestMessage.FromUserName + ".txt")); //执行微信处理过程 messageHandler.Execute(); //测试时可开启,帮助跟踪数据 messageHandler.ResponseDocument.Save(Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" + messageHandler.ResponseMessage.ToUserName + ".txt")); Content(messageHandler.ResponseDocument.ToString()); return; } catch (Exception ex) { using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".txt"))) { tw.WriteLine(ex.Message); tw.WriteLine(ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } tw.Flush(); tw.Close(); } Content(""); return; } } else { //get method if (CheckSignature.Check(signature, timestamp, nonce, Token)) { Content(echostr); //返回随机字符串则表示验证通过 return; } else { Content("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token)); return; } } }
public async Task <IActionResult> Post(PostModel postModel /*,[FromBody]string requestXml*/) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, token)) { return(Content("参数错误!")); } #region 打包 PostModel 信息 postModel.Token = token; //根据自己后台的设置保持一致 postModel.EncodingAESKey = encodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = appId; //根据自己后台的设置保持一致 #endregion //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 var maxRecordCount = 10; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 string body = new StreamReader(Request.Body).ReadToEnd(); byte[] requestData = Encoding.UTF8.GetBytes(body); Stream inputStream = new MemoryStream(requestData); //var inputStream = Request.Body; //byte[] buffer = new byte[Request.ContentLength ?? 0]; //inputStream.Read(buffer, 0, buffer.Length); //var requestXmlStream = new MemoryStream(buffer); //var requestXml = Encoding.UTF8.GetString(buffer); //int bytesRead = 0; //while ((bytesRead = Request.Body.Read(buffer, 0, buffer.Length)) != 0) //{ // inputStream.Write(buffer, 0, bytesRead); //} //Request.Body.CopyTo(inputStream); var messageHandler = new CustomMessageHandler(inputStream, postModel, _baseService, maxRecordCount); try { #region 记录 Request 日志 var logPath = Server.GetMapPath(string.Format("~/App_Data/MP/{0}/", DateTime.Now.ToString("yyyy-MM-dd"))); if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。 var requestDocumentFileName = Path.Combine(logPath, string.Format("{0}_Request_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName)); var ecryptRequestDocumentFileName = Path.Combine(logPath, string.Format("{0}_Request_Ecrypt_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName)); using (FileStream fs = new FileStream(requestDocumentFileName, FileMode.CreateNew, FileAccess.ReadWrite)) { messageHandler.RequestDocument.Save(fs); } if (messageHandler.UsingEcryptMessage) { using (FileStream fs = new FileStream(ecryptRequestDocumentFileName, FileMode.CreateNew, FileAccess.ReadWrite)) { messageHandler.EcryptRequestDocument.Save(fs); } } #endregion /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/ messageHandler.OmitRepeatedMessage = true; //执行微信处理过程 await messageHandler.ExecuteAsync(); #region 记录 Response 日志 //测试时可开启,帮助跟踪数据 //if (messageHandler.ResponseDocument == null) //{ // throw new Exception(messageHandler.RequestDocument.ToString()); //} var responseDocumentFileName = Path.Combine(logPath, string.Format("{0}_Response_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName)); var ecryptResponseDocumentFileName = Path.Combine(logPath, string.Format("{0}_Response_Final_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName)); if (messageHandler.ResponseDocument != null) { using (FileStream fs = new FileStream(responseDocumentFileName, FileMode.CreateNew, FileAccess.ReadWrite)) { messageHandler.ResponseDocument.Save(fs); } } if (messageHandler.UsingEcryptMessage && messageHandler.FinalResponseDocument != null) { using (FileStream fs = new FileStream(ecryptResponseDocumentFileName, FileMode.CreateNew, FileAccess.ReadWrite)) { //记录加密后的响应信息 messageHandler.FinalResponseDocument.Save(fs); } } #endregion ` //return Content(messageHandler.ResponseDocument.ToString());//v0.7- //return new WeixinResult(messageHandler);//v0.8+ return(new FixWeixinBugWeixinResult(messageHandler));//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 } catch (Exception ex) { #region 异常处理 WeixinTrace.Log("MessageHandler错误:{0}", ex.Message); _mongoLog.Add(ex); using (var fs = new FileStream(Server.GetMapPath("~/App_Data/Error_" + _getRandomFileName() + ".txt"), FileMode.CreateNew, FileAccess.ReadWrite)) { using (TextWriter tw = new StreamWriter(fs)) { tw.WriteLine("ExecptionMessage:" + ex.Message); tw.WriteLine(ex.Source); tw.WriteLine(ex.StackTrace); //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } if (ex.InnerException != null) { tw.WriteLine("========= InnerException ========="); tw.WriteLine(ex.InnerException.Message); tw.WriteLine(ex.InnerException.Source); tw.WriteLine(ex.InnerException.StackTrace); } tw.Flush(); //tw.Close(); } } return(Content("")); #endregion } }