CustomMessageContext.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Web;
  6. using Senparc.NeuChar.Context;
  7. using Senparc.NeuChar.Entities;
  8. using Senparc.Weixin.MP.Entities;
  9. using Senparc.Weixin.MP.Entities.Request;
  10. using Senparc.Weixin.MP.MessageHandlers;
  11. namespace EMIS.Utility.OnlinePay.WeChat
  12. {
  13. public class CustomMessageHandler : MessageHandler<CustomMessageContext>
  14. {
  15. public CustomMessageHandler(Stream inputStream, PostModel postModel)
  16. : base(inputStream, postModel)
  17. {
  18. }
  19. public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
  20. {
  21. var responseMessage = base.CreateResponseMessage<ResponseMessageText>(); //ResponseMessageText也可以是News等其他类型
  22. responseMessage.Content = "";
  23. return responseMessage;
  24. }
  25. public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
  26. {
  27. return base.OnEvent_SubscribeRequest(requestMessage);
  28. }
  29. public override IResponseMessageBase OnEvent_UnsubscribeRequest(RequestMessageEvent_Unsubscribe requestMessage)
  30. {
  31. return base.OnEvent_UnsubscribeRequest(requestMessage);
  32. }
  33. }
  34. public class CustomMessageContext : MessageContext<IRequestMessageBase, IResponseMessageBase>
  35. {
  36. public CustomMessageContext()
  37. {
  38. base.MessageContextRemoved += CustomMessageContext_MessageContextRemoved;
  39. }
  40. /// <summary>
  41. /// 当上下文过期,被移除时触发的时间
  42. /// </summary>
  43. /// <param name="sender"></param>
  44. /// <param name="e"></param>
  45. void CustomMessageContext_MessageContextRemoved(object sender, Senparc.NeuChar.Context.WeixinContextRemovedEventArgs<IRequestMessageBase, IResponseMessageBase> e)
  46. {
  47. /* 注意,这个事件不是实时触发的(当然你也可以专门写一个线程监控)
  48. * 为了提高效率,根据WeixinContext中的算法,这里的过期消息会在过期后下一条请求执行之前被清除
  49. */
  50. var messageContext = e.MessageContext as CustomMessageContext;
  51. if (messageContext == null)
  52. {
  53. return;//如果是正常的调用,messageContext不会为null
  54. }
  55. //TODO:这里根据需要执行消息过期时候的逻辑,下面的代码仅供参考
  56. //Log.InfoFormat("{0}的消息上下文已过期",e.OpenId);
  57. //api.SendMessage(e.OpenId, "由于长时间未搭理客服,您的客服状态已退出!");
  58. }
  59. }
  60. }