上一篇已經搭建好整體框架,實現了入口的驗證, 驗證通過後就交給LookMsgType方法處理,LookMsgType方法主要是對微信發來的不同的消息進行分解,不同的類型交給業務邏輯層不同的方法處理, 對不同類型的消息判斷,可以用if,也可以用switch 一般來說超過5個的if用switch會更好, 這裡貼出LookMsgType方法:
public void LookMsgType(string msgType) { #region 判斷消息類型 switch (msgType) { case "text": RText mText = new RText(); mText = ReadXml.GetModel<RText>(mText, xmlModel); BLLWei.DoText(dbHome, mText);//文本消息 break; case "image": RImg mImg = new RImg(); mImg = ReadXml.GetModel<RImg>(mImg, xmlModel); BLLWei.DoImg(dbHome,mImg);//圖片 break; case "voice": //聲音 RVoice mVoice = new RVoice(); mVoice = ReadXml.GetModel<RVoice>(mVoice, xmlModel); BLLWei.DoVoice(dbHome,mVoice); break; case "video"://視頻 RVideo mVideo = new RVideo(); mVideo = ReadXml.GetModel<RVideo>(mVideo, xmlModel); BLLWei.DoVideo(dbHome, mVideo); break; case "location"://地理位置 RLocation mLocation = new RLocation(); mLocation = ReadXml.GetModel<RLocation>(mLocation, xmlModel); BLLWei.DoLocation(dbHome,mLocation); break; case "link"://鏈接 RLink mLink = new RLink(); mLink = ReadXml.GetModel<RLink>(mLink, xmlModel); BLLWei.DoLink(dbHome,mLink); break; #region 事件 case "event": switch (ReadXml.ReadModel("Event", xmlModel)) { case "subscribe": if (ReadXml.ReadModel("EventKey", xmlModel).IndexOf("qrscene_") >= 0) { RCodeNotSub mNotSub = new RCodeNotSub(); mNotSub = ReadXml.GetModel<RCodeNotSub>(mNotSub, xmlModel); BLLWei.DoCodeNotSub(dbHome,mNotSub);//未關注的新用戶,掃描帶參數的二維碼關注 } else { RSub mSub = new RSub(); mSub = ReadXml.GetModel<RSub>(mSub, xmlModel); BLLWei.DoSub(dbHome,mSub);//普通關注 } break; case "unsubscribe": RUnsub mUnSub = new RUnsub (); mUnSub = ReadXml.GetModel<RUnsub>(mUnSub, xmlModel); BLLWei.DoUnSub(dbHome,mUnSub);//取消關注 break; case "SCAN": RCodeSub mCodeSub = new RCodeSub(); mCodeSub = ReadXml.GetModel<RCodeSub>(mCodeSub, xmlModel); BLLWei.DoCodeSub(dbHome,mCodeSub);//已經關注的用戶掃描帶參數的二維碼 break; case "LOCATION"://用戶上報地理位置 RSubLocation mSubLoc = new RSubLocation(); mSubLoc = ReadXml.GetModel<RSubLocation>(mSubLoc, xmlModel); BLLWei.DoSubLocation(dbHome, mSubLoc); break; case "CLICK"://自定義菜單點擊 RMenuClick mMenuClk = new RMenuClick(); mMenuClk = ReadXml.GetModel<RMenuClick>(mMenuClk, xmlModel); BLLWei.DoMenuClick(dbHome, mMenuClk); break; case "VIEW"://自定義菜單跳轉事件 RMenuView mMenuVw = new RMenuView(); mMenuVw = ReadXml.GetModel<RMenuView>(mMenuVw, xmlModel); BLLWei.DoMenuView(dbHome, mMenuVw); break; }; break; #endregion } #endregion }
外層switch判斷msgtype, 在event類型時,再次switch判斷具體的事件類型(關注、取消關注、自定義菜單事件等), 至此所有的微信發來的消息都有處理了,在上面代碼中用到消息模型以及ReadXml.GetModel方法給模型賦值, 賦值之後傳遞給業務邏輯層對應的方法處理, 下面寫出消息封裝和給模型賦值的方法。