Home > WeChat Applet > WeChat Development > Develop WeChat public platform with asp.net (2) Multi-layer architecture framework construction and entrance implementation

Develop WeChat public platform with asp.net (2) Multi-layer architecture framework construction and entrance implementation

高洛峰
Release: 2017-02-23 14:03:32
Original
2048 people have browsed it

We have designed a relatively complete database in the previous article, and this article starts with the code. First, execute the database script designed in the previous article in the database to generate the database, and then create the project in VS. In order to facilitate understanding and viewing, I designed very straightforward class names and file names without namespace prefixes.

Adopt interface method, a total of 8 projects: 7 class libraries and one MVC project, respectively:

                                                                                                                                                                                                                                                                                                                 to Access interface IBLL, specific implementation BLL                                                                                                                                                                                                                                                                                                                                                                                                     for

##                                                                                                                                                                                                                                                                           tityFramework context object and some cache management, business logic layer and data access I will hand over the interface production (implementation) work of the layer to Spring.NET injection implementation. After the framework is built, it is as follows:

After the framework is built, add the database and add it in DAL (note that DAL is not datamodel) New item, select data--ADO.NET entity data model:

Develop WeChat public platform with asp.net (2) Multi-layer architecture framework construction and entrance implementation Give it a name, let’s call it WeixinModel, select Generate from database, configure Connect the database to the previously generated database, follow the next step, and finally load it into edmx. Right-click on edmx - add code generation item, select code:

Select DbContext Generator, and then save Click edmx, then copy edmx and weixinmodel.tt to DataModel, delete edmx and weixinmodel.tt in DAL, open weixinmodel.tt in datamodel and save it. In addition, it needs to be declared in WeiXinModel.Context.cs retained in DAL. datamodel namespace.

Now that the framework and data model are available, add references according to the correct reference levels in DAL, IDAL, BLL, and IBLL, and write a few common methods, and then you can start using them in the display layer. Develop WeChat public platform with asp.net (2) Multi-layer architecture framework construction and entrance implementation

Here is an example of adding, deleting, modifying and checking methods in DAL:

//添加
        public T AddEntity<T>(DbContext db,T entity) where T : class
        {
            db.Entry<T>(entity).State = EntityState.Added;
            db.SaveChanges();
            return entity;
        }

        //修改
        public bool UpdateEntity<T>(DbContext db,T entity) where T : class
        {
            db.Set<T>().Attach(entity);
            db.Entry<T>(entity).State = EntityState.Modified;
            db.SaveChanges();
            return true;
        }
        //删除
        public bool DeleteEntity<T>(DbContext db,T entity) where T : class
        {
            db.Set<T>().Attach(entity);
            db.Entry<T>(entity).State = EntityState.Deleted;
            db.SaveChanges();
            return true;

        }




        // 返回一个对象
        public T InfoEntities<T>(DbContext db, Expression<Func<T, bool>> whereLambda) where T : class
        {

            return db.Set<T>().Where<T>(whereLambda).FirstOrDefault();

        }
Copy after login

Write the interface and business logic layer accordingly.

现在来到显示层,默认的MVC项目是返回VIEW, 这里我们不需要返回页面, 把home中的index改成Void返回类型, 接下去就是接收微信发来的请求进行判断了,验证请求----接收POST数据---分析XML----解析成自己想要的数据

  入口:首先验证消息来源是微信服务器,然后解析收到的xml,解析成功有数据则执行LookMsgType方法来进行处理

private IBLL.IDoWei BLLWei { set; get; }
        public DbContext dbHome { get; set; }
        private string token { get; set; }
        Dictionary<string, string> xmlModel = new Dictionary<string, string>();         
        public void Index()
        {
            dbHome=FContext.WeiXinDbContext(); 
            //xml字符串
            string xmlData = string.Empty;
            //请求类型
            string method=Request.HttpMethod.ToLower();
            string signature = Request.QueryString["signature"];
            string timestamp = Request.QueryString["timestamp"];
            string nonce = Request.QueryString["nonce"];
            //验证接入和每次请求验证真实性
            if (method == "get")
            {
                if (CheckSign(signature,timestamp,nonce))
                {
                    Often.ResponseToEnd(Request.QueryString["echostr"]);
                }
                else
                {
                    Response.Status = "403";
                    Often.ResponseToEnd("");
                }
            }
            //处理接收到的POST消息
            else if (method == "post")
            {
                using (Stream stream = Request.InputStream)
                {
                    Byte[] byteData = new Byte[stream.Length];
                    stream.Read(byteData, 0, (Int32)stream.Length);
                    xmlData = Encoding.UTF8.GetString(byteData);
                }
                if (!string.IsNullOrEmpty(xmlData))
                {
                    try
                    {
                        xmlModel = ReadXml.GetXmlModel(xmlData);
                    }
                    catch
                    {
                        //未能正确处理 给微信服务器回复默认值
                        Often.ResponseToEnd("");
                    }
                }
                if (xmlModel.Count > 0)
                {
                    string msgType = ReadXml.ReadModel("MsgType", xmlModel);
                    LookMsgType(msgType);
                }
            }
            else//除了post和get外 如head皆视为非法请求
            {
                Response.Status = "403";
                Often.ResponseToEnd("");  
            }
            dbHome.Dispose();
        }
Copy after login

这里用到的验证方法:

/// <summary>
        /// 验证签名
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <returns></returns>
        public bool CheckSign(string signature, string timestamp, string nonce)
        {
            List<string> list = new List<string>();
            list.Add(token);
            list.Add(timestamp);
            list.Add(nonce);
            //默认排序
            list.Sort();
            string tmpStr = string.Empty;
            list.All(l => { tmpStr += l; return true; });
            tmpStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            //验证
            if (tmpStr == signature)
            {
                return true;
            }
            return false;
        }
Copy after login

仓储中的EF上下文:

public static DbContext WeiXinDbContext()
        {
            DbContext dbcontext =new WeiXinEntities();  //创建
            dbcontext.Configuration.AutoDetectChangesEnabled = false;//自动检测配置更改
            dbcontext.Configuration.LazyLoadingEnabled = true;//延迟加载
            dbcontext.Configuration.ValidateOnSaveEnabled = false;//自动跟踪
            return dbcontext;
        }
Copy after login

Common中的解析微信发来的XML方法

//把接收到的XML转为字典
        public static Dictionary<string, string> GetXmlModel(string xmlStr)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlStr);
            Dictionary<string, string> mo = new Dictionary<string, string>();
            var data = doc.DocumentElement.ChildNodes;
            for (int i = 0; i < data.Count; i++)
            {
                mo.Add(data.Item(i).LocalName, data.Item(i).InnerText);
            }
            return mo;
        }



        ////从字典中读取指定的值
        public static string ReadModel(string key, Dictionary<string, string> model)
        {
            string str = "";
            model.TryGetValue(key, out str);
            if (str== null)
                str = "";
            return str;
        }
Copy after login

好了,入口以及验证相关的都解决了,下一篇开始微信消息处理LookMsgType方法实现

更多Develop WeChat public platform with asp.net (2) Multi-layer architecture framework construction and entrance implementation相关文章请关注PHP中文网!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template