asp.net微信公众平台开发实例演示
操作方法
- 01
using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.IO; using System.Xml; using System.Text; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string postStr = ""; if (Request.HttpMethod.ToLower() == "post") { Stream s = System.Web.HttpContext.Current.Request.InputStream; byte[] b = new byte[s.Length]; s.Read(b, 0, (int)s.Length); postStr = Encoding.UTF8.GetString(b); if (!string.IsNullOrEmpty(postStr)) { ResponseMsg(postStr); } } } /// <summary> /// 返回信息结果(微信信息返回) /// </summary> /// <param name="weixinXML"></param> private void ResponseMsg(string weixinXML) { //回复消息的部分:你的代码写在这里 XmlDocument doc = new XmlDocument(); doc.LoadXml(weixinXML); XmlNodeList list = doc.GetElementsByTagName("xml"); XmlNode xn = list[0]; string FromUserName = xn.SelectSingleNode("//FromUserName").InnerText; string ToUserName = xn.SelectSingleNode("//ToUserName").InnerText; string content = ""; content = xn.SelectSingleNode("//Content").InnerText; //string content = "";// doc.GetElementsByTagName("content").Item(0).ToString(); if (content.Equals("Hello2BizUser")) { content = "欢迎关注!"; } else { content = "现在是北京时间:" + string.Format("{0:f}", DateTime.Now); } string strresponse = "<xml>"; strresponse = strresponse + "<ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>"; strresponse = strresponse + "<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>"; strresponse = strresponse + "<CreateTime>" + DateTime.Now.Ticks.ToString() + "</CreateTime>"; strresponse = strresponse + "<MsgType><![CDATA[text]]></MsgType>"; strresponse = strresponse + "<Content><![CDATA[" + content + "]]></Content>"; strresponse = strresponse + "<FuncFlag>0<FuncFlag>"; strresponse = strresponse + "</xml>"; WriteLog("postStr:" + content); Response.Write(strresponse); } /// <summary> /// 写日志(用于跟踪) /// </summary> private void WriteLog(string strMemo) { if (!Directory.Exists(Server.MapPath(@"logs\"))) { Directory.CreateDirectory(Server.MapPath(@"logs\")); } string filename = Server.MapPath(@"logs/log.txt"); StreamWriter sr = null; try { if (!File.Exists(filename)) { sr = File.CreateText(filename); } else { sr = File.AppendText(filename); } sr.WriteLine(strMemo); } catch { } finally { if (sr != null) sr.Close(); } } }