当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net微信开发(自定义会话管理)

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

邮政速递物流查询,成功一试灵,ca1521航班

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

因为我试使用富文本文件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, this.gettype(), "", "alert('删除失败!');location='weixinsessionlist.aspx'", true);
   }
  }
  }
  if (!bools)
  {
  scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "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, this.gettype(), "", "alert('页码不能为空!')", true);
  this.txtpageindex.focus();
  return;
  }
  if (isnum(this.txtpageindex.text.tostring().trim()))
  {
  scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "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, this.gettype(), "", "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", access_token, null, datetime.now.addseconds(7000), 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微信开发教程汇总》,欢迎大家学习阅读。

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网