asp.net微信开发自定义会话管理

和微信用户的沟通少不了,总觉得看起来微信官网后台管理中的会话回复消息有点呆板,所以我这里就自定义了一个会话管理功能,最终效果图如下:

因为我试使用富文本文件CKEDITOR来进行编写,你看到稳中可能会有<P></p>字段,后台获取数据内容时,替换为空字符即可:如下

 string txtcontent = this.txtMessage.Value.ToString().Replace("<p>","");
   StringBuilder sb = new StringBuilder();
   sb.Append(txtcontent.Replace("</p>\r\n",""));

在我个人理解,做会话管理,无非就是将用户对话信息(用户发过来的数据,发给用户的数据)存入数据库,根据用户的数据时间和回复用户数据的时间来和当天系统的时间做对比,如果大于多少分钟或者多少个小时就不可以再主动和用户对话,就算我这里是根据微信官网48小时来进行限制的,超过48小时禁用控件,如下图:


废话少说,上代码:需要用到的两个类,数据库也要创建和类相同的名字(至少我试这么做的)
 

/// <summary>
 /// 微信会话记录类,用户存储会话记录列表
 /// </summary>
 public class WeixinKeFuInfo
 {
 public int UId { get; set; }//编号
 public string UserOpenId { get; set; }//用户的OpenID
 public string UserContent { get; set; }//用户内容
 public string CreaterDate { get; set; }//创建时间
 }

 

 /// <summary>
 /// 与微信用户会话的消息记录类
 /// </summary>
 public class WxMessageInfo
 {
 public int msgId { get; set; }//消息ID
 public string FromUser { get; set; }//发送用户
 public string ToUser { get; set; }//接收用户
 public string Content { get; set; }//发送内容
 public string FaSongDate { get; set; }//发送时间
 public string UId { get; set; }//会话用户的UId,微信会话记录类外键
 }

 /// <summary>
 /// 发送文本。。。。。。。。。。。。。还记得这个方法吗?就是根据用户发送过来的消息类型进行判断后,如果是文本就回复发送此方法内的内容
 /// </summary>
 /// <param name="requestXML"></param>
 private void SendTextCase(RequestXML requestXML)
 {

      WeixinKeFuService wkfs = new WeixinKeFuService();//自己写的服务类
  //根据openId查询数据库会话记录是否存在
  WeixinKeFuInfo wkfinfoinfo = wkfs.GetWeixinKeFuInfoByOpenId(requestXML.FromUserName.ToString());
  if (wkfinfoinfo != null)
  {
   //如果存在直接保存消息记录
   WxMessageService wms = new WxMessageService();
   WxMessageInfo wminfo = new WxMessageInfo();
   wminfo.FromUser = requestXML.FromUserName.ToString();
   wminfo.ToUser = "我";
   wminfo.Content = requestXML.Content.ToString();
   wminfo.FaSongDate = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
   wminfo.UId = wkfinfoinfo.UId.ToString();
   wms.AddWxMessageInfo(wminfo);
  }
  else
  {
   //如果不存在新建会话记录
   WeixinKeFuInfo wkfinfo = new WeixinKeFuInfo();
   wkfinfo.UserOpenId = requestXML.FromUserName.ToString();
   wkfinfo.UserContent = requestXML.Content.ToString();
   wkfinfo.CreaterDate = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
   wkfs.AddWeixinKeFuInfo(wkfinfo);

   string responseContent = FormatTextXML(requestXML.FromUserName,requestXML.ToUserName,"正在接入.请稍候.....");

   HttpContext.Current.Response.ContentType = "text/xml";
   HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
   HttpContext.Current.Response.Write(responseContent);
   HttpContext.Current.Response.End();
  }

  }

以上代码实现了数据库的插入,那么取出来,显示的页面,核心代码:WeiXinSessionList.aspx,前台代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WeiXinSessionList.aspx.cs" Inherits="DQWebSite.Administrator.WeiXinSessionList" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title></title>
 <meta http-equiv="refresh" content="60; url=WeiXinSessionList.aspx" />
 <link href="css/style.css" rel="Stylesheet" type="text/css" />
 <style type="text/css">
 .tablestyle { width:1124px; margin:10px auto 10px auto; border:1px solid #ecd9df; text-align:center;
 }
 th { height:35px;background-image:url('images/th.gif'); background-repeat:repeat-x;
 }
  tr { height:30px;
  }
  td {
  border-left:1px dotted #a7b5bc;
  }
 .trcolor { background-color:#ecd9df;
 }
 tr:hover { cursor:pointer;
 }
  #FenPage { width:1124px; height:25px; line-height:25px; text-align:center; margin:20px auto 20px auto;
 }
 .linka { color:#0094ff; cursor:pointer;
 }
 .fenyebtn {width:60px; height:25px; border:1px solid #ced9df; border-radius:5px; text-align:center; line-height:25px; float:right;
 }
 .fenyebtn2 { width:60px; height:25px; border:1px solid #ced9df; border-radius:5px; text-align:center; line-height:25px;margin-left:10px;float:right;
 }
 .toPageIndex { width:60px;height:25px; background-image:url('images/inputbg.gif'); margin-left:10px; background-repeat:repeat-x;border-top:solid 1px #a7b5bc; border-left:solid 1px #a7b5bc; border-right:solid 1px #ced9df; border-bottom:solid 1px #ced9df; text-align:center; float:right;
 }
 .gotoPagebtn { width:60px; height:25px; border:1px solid #ced9df; border-radius:5px; text-align:center; line-height:25px;margin-left:10px;float:right; background-color:#ced9df;
 }
 .deletebtn {float:left;width:100px; color:#000; height:25px; background-color:#ced9df; border:1px solid #ced9df; border-radius:5px; text-align:center;
 }
 #BtnDeleteSelected:hover { cursor:pointer;
 }
 .publishHuoDong {background-color:#ced9df; border:1px solid #ced9df; border-radius:5px;text-align:center; width:100px; color:#000; height:25px; line-height:25px; float:left;
 }
 a { color:#08a5e0;
 }
 .droplist { background-image:url('images/inputbg.gif'); background-repeat:repeat-x; width:120px; height:25px; border:1px solid #ced9df;
 }
 </style>
 <script type="text/javascript">
 
  function EditRoster(piciNumber) {
  var url = 'MessageWindow.aspx?id=' + piciNumber;    //转向网页的地址;
  var name = 'add';    //网页名称,可为空;
  var iWidth = 850;    //弹出窗口的宽度;
  var iHeight = 600;    //弹出窗口的高度;
  //获得窗口的垂直位置
  var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
  //获得窗口的水平位置
  var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
  window.open(url,name,'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=0,titlebar=no');
 
  }
 </script>
</head>
<body style="background-image:url('images/ygbg.png'); background-repeat:repeat;">
 <form id="form1" runat="server">
 <div class="place">
  <span>位置:</span>
  <ul class="placeul">
   <li><a href="WelCome.aspx" target="rightFrame">首页</a></li>
   <li>微信管理</li>
   <li>德桥员工服务中心--会话管理</li>
  </ul>
  </div>
 <div>
 <div style="width:1124px;margin:10px auto 0px 20px;">
  <font style="color:red;"> 根据微信公众平台规定,用户主送发起会话后,48小时之内可与该用户进行无限次会话,超过48小时不能主动会话。</font>
 </div>
 <asp:ScriptManager ID="ScriptManager1" runat="server">
 </asp:ScriptManager>
 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>
 <table class="tablestyle">
  <asp:Repeater ID="RepeaterGustBookList" runat="server" OnItemDataBound="RepeaterGustBookList_ItemDataBound">
  <HeaderTemplate>
  <tr>
   <th style="width:50px;"><asp:CheckBox ID="CheckAll" runat="server"
  oncheckedchanged="CheckAll_CheckedChanged" /><br /></th>
   <th style="width:105px;">openId</th>
<%--   <th style="width:150px;">昵称</th>
   <th style="width:50px;">性别</th>--%>
   <th style="width:200px;">初始内容</th>
   <th style="width:100px;">接入时间</th>
   <th style="width:100px;">近期会话</th>
   <th style="width:80px;">会话状态</th>
   <th style="width:150px;">已过时间</th>
   <th style="width:100px;">会话操作</th>
  </tr>
  </HeaderTemplate>
  <ItemTemplate>
  <tr style='%#(Container.ItemIndex%2==0)?"#fff":"#ced9ff"%>' >
   <td><asp:CheckBox ID="CheckIn" runat="server" /></td>
   <td><asp:Label ID="lbUId" runat="server" Visible="false" Text="Label"></asp:Label>
    <%# Eval("UserOpenId")%>
   </td>
<%--   <td><asp:Label ID="lbNikeName" runat="server" Text="未知"></asp:Label></td>
   <td><asp:Label ID="lbSex" runat="server" Text="未知"></asp:Label></td>--%>
   <td><%# (Eval("UserContent").ToString().Length>10)?Eval("UserContent").ToString().Substring(0,10)+"..":Eval("UserContent") %></td>
   <td><%# Eval("CreaterDate")%></td>
   <td><asp:Label ID="lblastDate" runat="server" Text="未知"></asp:Label></td>
   <td><asp:Label ID="lbState" runat="server" Text="未知"></asp:Label></td>
   <td><asp:Label ID="lbChaoshi" runat="server" Text="未知"></asp:Label></td>
   <td><a onclick="EditRoster(<%# Eval("UId") %>);">启动会话</a> 
<%--   <asp:HyperLink ID="HyperLinkNewSession" runat="server">新建</asp:HyperLink> --%>
   </td>
  </tr>
  </ItemTemplate>
 </asp:Repeater>
 </table>
  <div id="FenPage">
  <asp:LinkButton ID="LinkBtnToPage" CssClass="gotoPagebtn" runat="server" OnClick="LinkBtnToPage_Click">确定</asp:LinkButton>
  <asp:TextBox ID="txtPageIndex" CssClass="toPageIndex" runat="server"></asp:TextBox> 
  <asp:HyperLink ID="lnkLast" runat="server"><span class="fenyebtn2">>>|</span></asp:HyperLink> 
  <asp:HyperLink ID="lnkNext" runat="server"><span class="fenyebtn2">></span></asp:HyperLink> 
   <asp:HyperLink ID="lnkTop" runat="server"><span class="fenyebtn2"><</span></asp:HyperLink> 
  <asp:HyperLink ID="lnkFist" runat="server"><span class="fenyebtn">|<<</span></asp:HyperLink> 
  <asp:Button ID="BtnDelete" runat="server" Text="删除选中项" CssClass="deletebtn"
  BackColor="ButtonFace" onclick="BtnDelete_Click" />
  <span style="float:left;margin-left:20px;">当前第</span>
  <span style="float:left; color:red;"><asp:Label ID="lbPageIndex" runat="server" Text=""></asp:Label></span>
  <span style="float:left;margin-left:5px;">页/</span>
  <span style="float:left;margin-left:5px;">共</span>
  <span style="float:left;color:red;"><asp:Label ID="lbCountPage" runat="server" Text=""></asp:Label></span>
  <span style="float:left;margin-left:5px;">页</span>
  <span style="float:left;margin-left:10px;"><asp:Label ID="lbPageSize" runat="server" Text=""></asp:Label></span>
  <span style="float:left;margin-left:10px;">共搜索到 </span>
  <span style="float:left;margin-left:5px; color:red;"><asp:Label ID="lbCountData" runat="server" Text=""></asp:Label></span>
  <span style="float:left;margin-left:5px;">条记录.</span>
  </div>
  </ContentTemplate>
 </asp:UpdatePanel>
 </div>
 </form>
</body>
</html>

WeiXinSessionList.aspx.cs后台代码如下:

PagedDataSource pds = new PagedDataSource();
 protected void Page_Load(object sender,EventArgs e)
 {
  if (!Page.IsPostBack)
  {
  BindGustBookList();
  this.DataBind();
  UsersInfo user = Session["Users"] as UsersInfo;
  if (user != null && user.RolsId == 1)
  {
   this.BtnDelete.Enabled = true;
  }
  else
  {
   this.BtnDelete.Enabled = false;
  }
  }
 }
 private void BindGustBookList()
 {

  WeixinKeFuService wkf = new WeixinKeFuService();
  List<WeixinKeFuInfo> wkflists = wkf.GetAllWeixinKeFuInfoList();


  //if (this.DDLState.SelectedValue.Equals("1"))
  //{
  // lists = gbs.GetAllGustBookListByState();
  //}
  //else if (this.DDLState.SelectedValue.Equals("2"))
  //{
  // lists = gbs.GetAllGustBookListByState2();
  //}
  //else
  //{
  // lists = gbs.GetAllGustBookList();
  //}

  pds.DataSource = wkflists;
  pds.AllowPaging = true;
  pds.PageSize = 20;//每页显示为20条
  int CurrentPage;


  if (!String.IsNullOrWhiteSpace(this.txtPageIndex.Text.ToString().Trim()))
  {

  CurrentPage = Convert.ToInt32(this.txtPageIndex.Text.ToString().Trim());
  }
  else if (Request.QueryString["Page"] != null)
  {
  CurrentPage = Convert.ToInt32(Request.QueryString["Page"]);
  }
  else
  {
  CurrentPage = 1;
  }
  pds.CurrentPageIndex = CurrentPage - 1;//当前页的索引就等于当前页码-1;
  if (!pds.IsFirstPage)
  {
  //Request.CurrentExecutionFilePath 为当前请求的虚拟路径
  this.lnkTop.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(CurrentPage - 1);
  this.lnkFist.Enabled = this.lnkTop.Enabled = true;
  this.lnkNext.Enabled = this.lnkLast.Enabled = true;
  }
  else
  {
  this.lnkFist.Enabled = this.lnkTop.Enabled = false;
  this.lnkNext.Enabled = this.lnkLast.Enabled = true;
  this.lnkFist.Attributes.Add("style","color:#ced9df;");
  this.lnkTop.Attributes.Add("style","color:#ced9df;");
  this.lnkNext.Attributes.Remove("style");
  this.lnkLast.Attributes.Remove("style");
  }
  if (!pds.IsLastPage)
  {
  //Request.CurrentExecutionFilePath 为当前请求的虚拟路径
  this.lnkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(CurrentPage + 1);
  this.lnkFist.Enabled = this.lnkTop.Enabled = true;
  this.lnkNext.Enabled = this.lnkLast.Enabled = true;
  }
  else
  {
  this.lnkNext.Enabled = this.lnkLast.Enabled = false;
  this.lnkFist.Enabled = this.lnkTop.Enabled = true;
  this.lnkNext.Attributes.Add("style","color:#ced9df;");
  this.lnkLast.Attributes.Add("style","color:#ced9df;");
  this.lnkFist.Attributes.Remove("style");
  this.lnkTop.Attributes.Remove("style");
  }
  this.lnkFist.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(1);//跳转至首页
  this.lnkLast.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(pds.PageCount);//跳转至末页

  this.RepeaterGustBookList.DataSource = pds;
  this.RepeaterGustBookList.DataBind();

  this.lbCountData.Text = wkflists.Count.ToString();
  this.lbPageIndex.Text = (pds.CurrentPageIndex + 1).ToString();
  this.lbPageSize.Text = "每页" + pds.PageSize.ToString() + "条记录";
  this.lbCountPage.Text = pds.PageCount.ToString();
  this.txtPageIndex.Text = (pds.CurrentPageIndex + 1).ToString();

  if (int.Parse(wkflists.Count.ToString()) <= int.Parse(pds.PageSize.ToString()))
  {
  this.lnkFist.Visible = this.lnkTop.Visible = this.lnkNext.Visible = this.lnkLast.Visible = this.txtPageIndex.Visible = this.LinkBtnToPage.Visible = false;
  }
  else
  {
  this.lnkFist.Visible = this.lnkTop.Visible = this.lnkNext.Visible = this.lnkLast.Visible = this.txtPageIndex.Visible = this.LinkBtnToPage.Visible = true;
  }

 }
 /// <summary>
 /// 删除选中
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void BtnDelete_Click(object sender,EventArgs e)
 {
  Boolean bools = false;
  foreach (RepeaterItem di in this.RepeaterGustBookList.Items)
  {
  CheckBox checkIn = (CheckBox)di.FindControl("CheckIn");
  if (checkIn.Checked)
  {
   bools = true;
   Label lbGustNo = di.FindControl("lbUId") as Label;
   WeixinKeFuService wkf = new WeixinKeFuService();
   int num = wkf.DeleteWeixinKeFuInfo(int.Parse(lbGustNo.Text.ToString()));
   if (num > 0)
   {
   ScriptManager.RegisterClientScriptBlock(this.Page,this.GetType(),"","alert('删除成功!');location='WeiXinSessionList.aspx'",true);
   }
   else
   {
   ScriptManager.RegisterClientScriptBlock(this.Page,"alert('删除失败!');location='WeiXinSessionList.aspx'",true);
   }
  }
  }
  if (!bools)
  {
  ScriptManager.RegisterClientScriptBlock(this.Page,"alert('未选中删除项!');location='WeiXinSessionList.aspx'",true);
  }
 }
 /// <summary>
 /// 全选全不选
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void CheckAll_CheckedChanged(object sender,EventArgs e)
 {
  CheckBox checkAll = (CheckBox)sender;
  foreach (RepeaterItem d in this.RepeaterGustBookList.Items)
  {
  CheckBox checkIn = (CheckBox)d.FindControl("CheckIn");
  checkIn.Checked = checkAll.Checked;
  }
 }
 protected void LinkBtnLook_Click(object sender,EventArgs e)
 {
  BindGustBookList();
 }
 /// <summary>
 /// 绑定事件
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void RepeaterGustBookList_ItemDataBound(object sender,RepeaterItemEventArgs e)
 {


  if (e.Item.ItemType == ListItemType.Header)
  {
  CheckBox checkAll = e.Item.FindControl("CheckAll") as CheckBox;
  checkAll.AutoPostBack = true;
  }
  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
  {
  WeixinKeFuInfo wkf = e.Item.DataItem as WeixinKeFuInfo;

   Label lbUId = e.Item.FindControl("lbUId") as Label;
   lbUId.Text = wkf.UId.ToString();

   WxMessageService wms = new WxMessageService();
   WxMessageInfo wminfo = wms.GetTopLastFaSongDateByUId(lbUId.Text.ToString());

   if(wminfo!=null&&!String.IsNullOrWhiteSpace(wminfo.FaSongDate.ToString()))
   {
   Label lblastDate = e.Item.FindControl("lblastDate") as Label;

   lblastDate.Text = wminfo.FaSongDate.ToString();

   DateTime datesystemss = DateTime.Parse(System.DateTime.Now.ToString());
   DateTime lastLoingDatess = DateTime.Parse(lblastDate.Text.ToString());

   TimeSpan ts11 = new TimeSpan(datesystemss.Ticks);
   TimeSpan ts22 = new TimeSpan(lastLoingDatess.Ticks);

   TimeSpan ts33 = ts11.Subtract(ts22).Duration();

   Label lbState = e.Item.FindControl("lbState") as Label;

   string chaoshifenzhong = ts33.TotalMinutes.ToString();

   if (double.Parse(chaoshifenzhong) <=10)
   {
    lbState.Text = "会话中";
    lbState.Attributes.Add("style","color:red;");
   }
   else
   {
    lbState.Text = "已结束";
   }


   Label lbChaoshi = e.Item.FindControl("lbChaoshi") as Label;

   DateTime datesystem = DateTime.Parse(System.DateTime.Now.ToString());
   DateTime lastLoingDate = DateTime.Parse(lblastDate.Text.ToString());

   TimeSpan ts1 = new TimeSpan(datesystem.Ticks);
   TimeSpan ts2 = new TimeSpan(lastLoingDate.Ticks);

   TimeSpan ts3 = ts1.Subtract(ts2).Duration();

   lbChaoshi.Text = ts3.Days.ToString() + "天" + ts3.Hours.ToString() + "小时" + ts3.Minutes.ToString() + "分钟";
   }

   //////根据用户的openId获取用户昵称

   //WeiXinServer wxs = new WeiXinServer();

   /////从缓存读取accesstoken
   //string Access_token = Cache["Access_token"] as string;

   //if (Access_token == null)
   //{
   // //如果为空,重新获取
   // Access_token = wxs.GetAccessToken();

   // //设置缓存的数据7000秒后过期
   // Cache.Insert("Access_token",Access_token,null,DateTime.Now.AddSeconds(7000),System.Web.Caching.Cache.NoSlidingExpiration);
   //}

   //string Access_tokento = Access_token.Substring(17,Access_token.Length - 37);

   //string jsonres = "";


   //jsonres = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + Access_tokento + "&openid=" + wkf.UserOpenId;

   //HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(jsonres);
   //myRequest.Method = "GET";
   //HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
   //StreamReader reader = new StreamReader(myResponse.GetResponseStream(),Encoding.UTF8);
   //string content = reader.ReadToEnd();
   //reader.Close();

   ////使用前需药引用Newtonsoft.json.dll文件
   //JObject jsonObj = JObject.Parse(content);


   //Label lbNikeName = e.Item.FindControl("lbNikeName") as Label;
   //Label lbSex = e.Item.FindControl("lbSex") as Label;
   //lbNikeName.Text = jsonObj["nickname"].ToString();
   //if (jsonObj["sex"].ToString().Equals("1"))
   //{
   // lbSex.Text = "男";
   //}
   //else
   //{
   // lbSex.Text = "女";
   //}

  }
 }
 /// <summary>
 /// 输入页码提交跳转
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void LinkBtnToPage_Click(object sender,EventArgs e)
 {

  if (String.IsNullOrWhiteSpace(this.txtPageIndex.Text.ToString().Trim()))
  {
  ScriptManager.RegisterClientScriptBlock(this.Page,"alert('页码不能为空!')",true);
  this.txtPageIndex.Focus();
  return;
  }
  if (IsNum(this.txtPageIndex.Text.ToString().Trim()))
  {
  ScriptManager.RegisterClientScriptBlock(this.Page,"alert('页码数只能输入数字!')",true);
  this.txtPageIndex.Focus();
  this.txtPageIndex.Text = this.lbPageIndex.Text.ToString();
  return;
  }
  if (int.Parse(this.txtPageIndex.Text.ToString().Trim()) > int.Parse(this.lbCountPage.Text.ToString().Trim()))
  {
  ScriptManager.RegisterClientScriptBlock(this.Page,"alert('所输页数不能大于总页数!')",true);
  this.txtPageIndex.Focus();
  this.txtPageIndex.Text = this.lbPageIndex.Text.ToString();
  return;
  }

  BindGustBookList();
 }
 /// <summary>
 /// 判断是否是数字
 /// </summary>
 /// <param name="text"></param>
 /// <returns></returns>
 public static bool IsNum(string text) //
 {
  for (int i = 0; i < text.Length; i++)
  {
  if (!Char.IsNumber(text,i))
  {
   return true; //输入的不是数字 
  }
  }
  return false; //否则是数字
 }

此代码已包含,后台分页功能,仔细研究下,即可使用.
点击开启会话的页面:MessageWindow.aspx如下:

<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false" CodeBehind="MessageWindow.aspx.cs" Inherits="DQWebSite.Administrator.MessageWindow" %> 
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <title></title>
 <style type="text/css">
 .messagestyle { width:100%; height:60px; margin-top:10px;
 }
  #LinkBtnSubSend { float:left;
  }
 /*.weixiao{ float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:0px 0px; width:30px; height:28px;
 }
 .piezui { float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:-31px -0px; width:30px; height:28px;
 }
 .hanxiao {float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:-0px -62px; width:30px; height:28px;
 }
 .zhuakuang {float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:-218px -62px; width:28px; height:28px;
 }
  .shuai {float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:-248px -62px; width:28px; height:28px;
 }
  .yiwen {float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:-126px -62px; width:28px; height:28px;
  }
  .liuhan {float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:-404px -30px; width:28px; height:28px;
  }*/
 a:hover { cursor:pointer;
 }
  .LinkBtnSubSend { margin-top:5px;
  }
 </style>
 <script type="text/javascript">
 
  function LessThan(oTextArea) {
 
  //获得textarea的maxlength属性
  var num = oTextArea.getAttribute("maxlength") - oTextArea.value.length;
 
  document.getElementById("errmsg").innerHTML = "还可输入的字符数:" + num;
 
  //返回文本框字符个数是否符号要求的boolean值
  return oTextArea.value.length < oTextArea.getAttribute("maxlength");
  }
 </script>
 <script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
 <script src="../ckeditor_4.5.4_full2/ckeditor/ckeditor.js"></script>
</head>
<body>
 <form id="form1" runat="server">
 <div style="height:30px; text-align:left;"> <asp:Label ID="lbduihua1" runat="server" Text="Label"></asp:Label> <span style="color:red;"><asp:Label ID="lbduihuamsg" runat="server" Text="Label"></asp:Label></span> <asp:Label ID="lbduihua2" runat="server" Text="Label"></asp:Label></div>
 <div style="height:200px; width:100%; border:2px groove #ced9df; border-top-left-radius:5px; border-top-right-radius:5px; overflow-y:auto;background-image:url('images/ygbg.png'); background-repeat:repeat;">
 <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>
  <ul>
   <asp:Repeater ID="RepeaterMessageList" runat="server" OnItemDataBound="RepeaterMessageList_ItemDataBound" >
   <ItemTemplate>
    <li><span style="color:red;">
    <asp:Label ID="lbFromUser" runat="server" Text="Label"></asp:Label> </span>对<span style="color:red;"><%# Eval("ToUser") %></span>说:
    <asp:Image ID="Imagelaba" runat="server" />
    <br />
    <%# Eval("Content") %> [<%# Eval("FaSongDate") %>]<br />
    </li>
   </ItemTemplate>
   </asp:Repeater> 
  </ul>
   <asp:Timer ID="timeTick" runat="server" Interval="200" OnTick="timeTick_Tick"></asp:Timer>
  </ContentTemplate>
 </asp:UpdatePanel>
 </div>
 <textarea id="txtMessage" name="txtMessage" runat="server" class="ckeditor messagestyle" maxlength="200" onkeypress="return LessThan(this);" onchange="return LessThan(this);"></textarea>
  <script type="text/javascript">CKEDITOR.replace('<%=txtMessage.ClientID.Replace("_","$") %>');</script>
  <div style="height:35px; line-height:35px;">
  <asp:LinkButton ID="LinkBtnSubSend" CssClass="LinkBtnSubSend" runat="server" OnClick="LinkBtnSubSend_Click"><div style="background-image:url('images/buttonbg.png'); width:111px; height:35px; line-height:35px; font-weight:bold; text-align:center; float:left; color:#fff;">发送</div></asp:LinkButton>
  <span id="errmsg" style="color:red;" runat="server" >该推送功能直接将信息推送到对方用户微信,谨慎发言</span>
  </div>
 </form>
</body>
</html>

MessageWindow.aspx.cs的核心代码如下:

protected void Page_Load(object sender,EventArgs e)
 {
  if(!Page.IsPostBack)
  {
  if(Request.QueryString["id"]!=null)
  {
   WeixinKeFuService wkfs = new WeixinKeFuService();

   WeixinKeFuInfo wkfinfo = wkfs.GetWeixinKeFuInfoByid(int.Parse(Request.QueryString["id"].ToString()));
   this.lbduihuamsg.Text = wkfinfo.UserOpenId.ToString();

   this.lbduihua1.Text = "正在于";
   this.lbduihua2.Text = "对话中.......";

   WxMessageService wms = new WxMessageService();
   WxMessageInfo wminfo = wms.GetTopLastFaSongDateByUId(wkfinfo.UId.ToString());


   if (wminfo != null)
   {

   DateTime datesystemss = DateTime.Parse(System.DateTime.Now.ToString());
   DateTime lastLoingDatess = DateTime.Parse(wminfo.FaSongDate.ToString());

   TimeSpan ts11 = new TimeSpan(datesystemss.Ticks);
   TimeSpan ts22 = new TimeSpan(lastLoingDatess.Ticks);

   TimeSpan ts33 = ts11.Subtract(ts22).Duration();

   string chaodays = ts33.TotalDays.ToString();

   if (double.Parse(chaodays) >=2)
   {
    this.LinkBtnSubSend.Enabled = false;
    this.errmsg.InnerText = "会话已结束!超过48小时不能主动推送信息给该用户!";
    this.lbduihua1.Text = "已经于";
    this.lbduihua2.Text = "失去连接.....除非该用户主动会话才能重新建立连接!";
    this.txtMessage.Attributes.Add("readonly","true");
   }
   }

   BindMsgList();

   this.DataBind();
  }
  }
 }

 private void BindMsgList()
 {
  string id = Request.QueryString["id"].ToString();


  WxMessageService wms = new WxMessageService();

  List<WxMessageInfo> wmlist = wms.GetAllMessageList(id);

  if(wmlist.Count>0)
  {
  this.RepeaterMessageList.DataSource = wmlist;
  this.RepeaterMessageList.DataBind();
  }

 }

 protected void timeTick_Tick(object sender,EventArgs e)
 {
  BindMsgList();
 }
 /// <summary>
 /// 推送消息到用户
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void LinkBtnSubSend_Click(object sender,EventArgs e)
 {
  if(String.IsNullOrWhiteSpace(this.txtMessage.Value.ToString().Trim()))
  {
  this.errmsg.InnerText = "发送的内容不能为空!";
  this.txtMessage.Focus();
  return;
  }
  if (this.txtMessage.Value.ToString().Length < 5 || this.txtMessage.Value.ToString().Length > 200)
  {
  this.errmsg.InnerText = "发送内容应在5-200个字符之间!";
  this.txtMessage.Focus();
  return;
  }

  //如果存在直接保存消息记录
  WxMessageService wms = new WxMessageService();
  WxMessageInfo wminfo = new WxMessageInfo();
  wminfo.FromUser = "我";
  wminfo.ToUser = this.lbduihuamsg.Text.ToString();
  wminfo.Content = this.txtMessage.Value.ToString().Trim();
  wminfo.FaSongDate = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
  wminfo.UId = Request.QueryString["id"].ToString();
  wms.AddWxMessageInfo(wminfo);



  WeiXinServer wxs = new WeiXinServer();
  string res = "";

  ///从缓存读取accesstoken
  string Access_token = Cache["Access_token"] as string;

  if(Access_token==null)
  {
  //如果为空,重新获取
  Access_token = wxs.GetAccessToken();

  //设置缓存的数据7000秒后过期
  Cache.Insert("Access_token",System.Web.Caching.Cache.NoSlidingExpiration);
  }


  string Access_tokento = Access_token.Substring(17,Access_token.Length - 37);

  string txtcontent = this.txtMessage.Value.ToString().Replace("<p>","");
  StringBuilder sb = new StringBuilder();
  sb.Append(txtcontent.Replace("</p>\r\n",""));

  string posturl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + Access_tokento;
  string postData = "{\"touser\":\"" + this.lbduihuamsg.Text.ToString() + "\",\"msgtype\":\"text\",\"text\":{\"content\":\"" + sb.ToString() + "\"}}";
  res = wxs.GetPage(posturl,postData);


  //使用前需药引用Newtonsoft.json.dll文件
  JObject jsonObj = JObject.Parse(res);

  ///获取返回结果的正确|true|false
  string isright = jsonObj["errcode"].ToString();//0
  string istrueorfalse = jsonObj["errmsg"].ToString();//ok
  if (isright.Equals("0") && istrueorfalse.Equals("ok"))
  {
  this.errmsg.InnerText = "消息推送成功!消息已送达微信用户!";
  this.txtMessage.Value = "";
  }
  else
  {
  this.errmsg.InnerText = "消息推送失败!消息已保存至数据库!";
  }
 }

 protected void RepeaterMessageList_ItemDataBound(object sender,RepeaterItemEventArgs e)
 {
  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
  {
  WxMessageInfo wminfo = e.Item.DataItem as WxMessageInfo;

  Image Imagelaba = e.Item.FindControl("Imagelaba") as Image;

  Label lbFromUser = e.Item.FindControl("lbFromUser") as Label;

  lbFromUser.Text = wminfo.FromUser.ToString();


  if (wminfo.FromUser.ToString().Equals("我"))
  {
   Imagelaba.ImageUrl = "images/fa.gif";
  }
  else
  {
   Imagelaba.ImageUrl = "images/shou.gif";
  }

  }
 }

本文已被整理到了《ASP.NET微信开发教程汇总》,欢迎大家学习阅读。

以上就是会话管理功能的全部核心代码,仅供参考,希望对大家的学习有所帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


项目中经常遇到CSV文件的读写需求,其中的难点主要是CSV文件的解析。本文会介绍CsvHelper、TextFieldParser、正则表达式三种解析CSV文件的方法,顺带也会介绍一下CSV文件的写方法。 CSV文件标准 在介绍CSV文件的读写方法前,我们需要了解一下CSV文件的格式。 文件示例 一
简介 本文的初衷是希望帮助那些有其它平台视觉算法开发经验的人能快速转入Halcon平台下,通过文中的示例开发者能快速了解一个Halcon项目开发的基本步骤,让开发者能把精力完全集中到算法的开发上面。 首先,你需要安装Halcon,HALCON 18.11.0.1的安装包会放在文章末尾。安装包分开发和
这篇文章主要简单记录一下C#项目的dll文件管理方法,以便后期使用。 设置dll路径 参考C#开发奇技淫巧三:把dll放在不同的目录让你的程序更整洁中间的 方法一:配置App.config文件的privatePath : &lt;runtime&gt; &lt;assemblyBinding xml
在C#中的使用JSON序列化及反序列化时,推荐使用Json.NET——NET的流行高性能JSON框架,当然也可以使用.NET自带的 System.Text.Json(.NET5)、DataContractJsonSerializer、JavaScriptSerializer(不推荐)。
事件总线是对发布-订阅模式的一种实现,是一种集中式事件处理机制,允许不同的组件之间进行彼此通信而又不需要相互依赖,达到一种解耦的目的。&#xA;EventBus维护一个事件的字典,发布者、订阅者在事件总线中获取事件实例并执行发布、订阅操作,事件实例负责维护、执行事件处理程序。
通用翻译API的HTTPS 地址为https://fanyi-api.baidu.com/api/trans/vip/translate,使用方法参考通用翻译API接入文档 。&#xA;请求方式可使用 GET 或 POST 方式(Content-Type 请指定为:application/x-www-for
词云”由美国西北大学新闻学副教授、新媒体专业主任里奇·戈登(Rich Gordon)于2006年最先使用,是通过形成“关键词云层”或“关键词渲染”,对文本中出现频率较高的“关键词”的视觉上的突出。词云图过滤掉大量的文本信息,使浏览者只要一眼扫过文本就可以领略文本的主旨。&#xA;网上大部分文章介绍的是使用P
微软在.NET中对串口通讯进行了封装,我们可以在.net2.0及以上版本开发时直接使用SerialPort类对串口进行读写操作。&#xA;为操作方便,本文对SerialPort类做了一些封装,暂时取名为**SerialPortClient**。
简介 管道为进程间通信提供了平台, 管道分为两种类型:匿名管道、命名管道,具体内容参考.NET 中的管道操作。简单来说,匿名管道只能用于本机的父子进程或线程之间,命名管道可用于远程主机或本地的任意两个进程,本文主要介绍命名管道的用法。 匿名管道在本地计算机上提供进程间通信。 与命名管道相比,虽然匿名
目录自定义日志类NLog版本的日志类Serilog版本的日志类 上个月换工作,新项目又要重新搭建基础框架,把日志实现部分单独记录下来方便以后参考。 自定义日志类 代码大部分使用ChatGPT生成,人工进行了测试和优化,主要特点: 线程安全,日志异步写入文件不影响业务逻辑 支持过期文件自动清理,也可自
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机自动启动的两种常用方法](https://blog.csdn.net/weixin_42288432/article/details/120059296),将里面中的第一种方法做了封装成**AutoStart**类,使
简介 FTP是FileTransferProtocol(文件传输协议)的英文简称,而中文简称为“文传协议”。用于Internet上的控制文件的双向传输。同时,它也是一个应用程序(Application)。基于不同的操作系统有不同的FTP应用程序,而所有这些应用程序都遵守同一种协议以传输文件。 FTP
使用特性,可以有效地将元数据或声明性信息与代码(程序集、类型、方法、属性等)相关联。 将特性与程序实体相关联后,可以在运行时使用反射这项技术查询特性。&#xA;在 C# 中,通过用方括号 ([]) 将特性名称括起来,并置于应用该特性的实体的声明上方以指定特性。
# 简介 主流的识别库主要有ZXing.NET和ZBar,OpenCV 4.0后加入了QR码检测和解码功能。本文使用的是ZBar,同等条件下ZBar识别率更高,图片和部分代码参考[在C#中使用ZBar识别条形码](https://www.cnblogs.com/w2206/p/7755656.htm
C#中Description特性主要用于枚举和属性,方法比较简单,记录一下以便后期使用。 扩展类DescriptionExtension代码如下: using System; using System.ComponentModel; using System.Reflection; /// &lt;
本文实现一个简单的配置类,原理比较简单,适用于一些小型项目。主要实现以下功能:保存配置到json文件、从文件或实例加载配置类的属性值、数据绑定到界面控件。&#xA;一般情况下,项目都会提供配置的设置界面,很少手动更改配置文件,所以选择以json文件保存配置数据。
前几天用SerialPort类写一个串口的测试程序,关闭串口的时候会让界面卡死。网上大多数方法都是定义2个bool类型的标记Listening和Closing,关闭串口和接受数据前先判断一下。我的方法是DataReceived事件处理程序用this.BeginInvoke()更新界面,不等待UI线程
约束告知编译器类型参数必须具备的功能。 在没有任何约束的情况下,类型参数可以是任何类型。 编译器只能假定 System.Object 的成员,它是任何 .NET 类型的最终基类。 如果客户端代码使用不满足约束的类型,编译器将发出错误。 通过使用 where 上下文关键字指定约束。&#xA;最常用的泛型约束为
protobuf-net是用于.NET代码的基于契约的序列化程序,它以Google设计的“protocol buffers”序列化格式写入数据,适用于大多数编写标准类型并可以使用属性的.NET语言。&#xA;protobuf-net可通过NuGet安装程序包,也可直接访问github下载源码:https:/
工作中经常遇到需要实现TCP客户端或服务端的时候,如果每次都自己写会很麻烦且无聊,使用SuperSocket库又太大了。这时候就可以使用SimpleTCP了,当然仅限于C#语言。&#xA;SimpleTCP是一个简单且非常有用的 .NET 库,用于处理启动和使用 TCP 套接字(客户端和服务器)的重复性任务