加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

mvc项目架构分享系列之架构搭建之Infrastructure 架

发布时间:2020-12-16 09:00:38 所属栏目:asp.Net 来源:网络整理
导读:项目架构搭建之 Infrastructure 的搭建 Contents ? 系列一【架构概览】 0.项目简介 1.项目解决方案分层方案? 2.所用到的技术 3.项目引用关系? ? 系列二【架构搭建初步】 4.项目架构各部分解析 5.项目创建? ? 系列三 【Infrastructure搭建】 6.项目架构搭建之

项目架构搭建之Infrastructure的搭建

Contents

?

系列一【架构概览】

0.项目简介

1.项目解决方案分层方案?

2.所用到的技术

3.项目引用关系?

?

系列二【架构搭建初步】

4.项目架构各部分解析

5.项目创建?

?

系列三 【Infrastructure搭建】

6.项目架构搭建之Core搭建

7.项目架构搭建之Models搭建

?

系列四 【Repository和Service的搭建】

8.项目架构搭建之IDAL搭建?
9.项目架构搭建之MSSQLDAL搭建
10.项目架构搭建之IBLL搭建
11.项目架构搭建之BLL搭建

?

?

系列五 【UI搭建】

12.WebHelper搭建

13.Web搭建

14.AdminLogic搭建

?

系列六 【项目扩展】

15.新增Model的处理

?

?

6.项目架构搭建之Core搭建

????添加对用到的类库的引用,这里用到的包括:.NET自带的两个类库System.Configuration 、 System.Web ,和两个第三方类库 log4net(日志框架) 和 Newtonsoft.Json (Json.Net)

?

  • ConfigurationHelper 【配置文件帮助类】

?  

  1     /// <summary>
  2 
  3        /// 网站根路径
  4 
  5        </summary>
  6 
  7        private static string siteroot = System.Web.Hosting.HostingEnvironment.MapPath("~/");
  8 
  9  
 10 
 11         12 
 13         获取配置文件中AppSetting节点的相对路径对应的绝对路径
 14 
 15         16 
 17        <param name="key">相对路径设置的键值</param>
 18 
 19        <returns>绝对路径</returns>
 20 
 21        public string AppSettingMapPath(string key)
 22 
 23        {
 24 
 25            if (String.IsNullOrEmpty(siteroot))
 26 
 27            {
 28 
 29                siteroot = System.Web.Hosting.HostingEnvironment.MapPath( 30 
 31            }
 32 
 33            //拼接路径
 34 
 35            string path = siteroot + System.Configuration.ConfigurationManager.AppSettings[key].ToString();
 36 
 37            return path;
 38 
 39        }
 40 
 41  
 42 
 43         44 
 45         将虚拟路径转换为物理路径
 46 
 47         48 
 49        <param name="virtualPath">虚拟路径 50 
 51        虚拟路径对应的物理路径 52 
 53        string MapPath( virtualPath)
 54 
 55  56 
 57             58 
 59  60 
 61                siteroot = System.Web.Hosting.HostingEnvironment.MapPath( 62 
 63  64 
 65             66 
 67             virtualPath;
 68 
 69             70 
 71  72 
 73  
 74 
 75         76 
 77         获取配置文件中AppSetting节点的值
 78 
 79         80 
 81        设置的键值 82 
 83        键值对应的值 84 
 85        string AppSetting(string key) => 86 
 87  
 88 
 89         90 
 91         获取配置文件中ConnectionStrings节点的值
 92 
 93         94 
 95        键值 96 
 97        键值对应的连接字符串值 98 
 99        string ConnectionString( System.Configuration.ConfigurationManager.ConnectionStrings[key].ConnectionString;
100 
101  
102 
103        bool UpdateAppSettings(string key, value)
104 
105 106 
107            string filename = System.Web.Hosting.HostingEnvironment.MapPath(~/web.config108 
109            XmlDocument xmldoc = new XmlDocument();
110 
111            try
112 
113 114 
115                xmldoc.Load(filename);
116 
117 118 
119            catch (Exception)
120 
121 122 
123                return false;
124 
125 126 
127            XmlNodeList DocdNodeNameArr = xmldoc.DocumentElement.ChildNodes;文档节点名称数组
128 
129            foreach (XmlElement element in DocdNodeNameArr)
130 
131 132 
133                if (element.Name == appSettings")找到名称为 appSettings 的节点
134 
135                {
136 
137                    XmlNodeList KeyNameArr = element.ChildNodes;子节点名称数组
138 
139                    if (KeyNameArr.Count > 0)
140 
141                    {
142 
143                        foreach (XmlElement xmlElement  KeyNameArr)
144 
145                        {
146 
147                            找到键值,修改为想要修改的值
148 
149                            if (xmlElement.Attributes[key].InnerXml.Equals(key))
150 
151                            {
152 
153                                xmlElement.Attributes[value"].Value = value;
154 
155                                ConfigurationManager.RefreshSection(156 
157                                true158 
159                            }
160 
161                        }
162 
163                        没有相应的节点
164 
165                        166 
167                    }
168 
169                    else
170 
171 172 
173                        不存在 AppSettings 节点
174 
175                        176 
177 178 
179                }
180 
181 182 
183            184 
185 186 
187  

?

  • PathHelper 【路径帮助类】

    通过 System.Web.Hosting.HostingEnvironment.MapPath() 方法将虚拟路径转换为物理路径

?

1 2 3 4 5 6 string virtualPath) => System.Web.Hosting.HostingEnvironment.MapPath(") + virtualPath;

?

  • LogHelper????【日志帮助类】

    根据log4net中的ILog接口中的方法进行封装,在构造函数中设置logger,在程序启动时需要进行log4net的初始化,只初始化一次就可以了所以需要设置为static 静态方法

?

<summary>
    日志助手
   </summary>
   class LogHelper
   {
       readonly ILog logger = null;
 

       public LogHelper(Type t)
       {
           logger = LogManager.GetLogger(t);
       }
 

       public LogHelper( name)
       {
           logger = LogManager.GetLogger(name);
       }
 

       void LogInit()
       {
           log4net.Config.XmlConfigurator.Configure();
       }
 

       void Debug( msg)
       {
           logger.Debug(msg);
       }
 

        msg,Exception ex)
       {
           logger.Debug(msg,ex);
       }
 

       void Error( msg)
       {
           logger.Error(msg);
       }
 

       void Warn( msg)
       {
           logger.Warn(msg);
       }
 

        Debug(Exception ex)
       {
           logger.Debug(ex.Message,1)"> Error(Exception ex)
       {
           logger.Error(ex.Message,ex);
       }
   }

?

  • WebHelper 【Web帮助类】

    包括Web编码解码:html编码解码、url编码解码,Cookies管理,获取客户端信息(IP,浏览器类型、操作系统等信息)

    ?

     1 #region 编码
     2 
     3          4          HTML解码
     5          6         <returns></returns>
     7         string HtmlDecode( s)
     8         {
     9              HttpUtility.HtmlDecode(s);
    10         }
    11 
    12         13          HTML编码
    14         15         16         string HtmlEncode(17 18              HttpUtility.HtmlEncode(s);
    19 20 
    21         22          URL解码
    23         24         25         string UrlDecode(26 27              HttpUtility.UrlDecode(s);
    28 29 
    30         31          URL编码
    32         33         34         string UrlEncode(35 36              HttpUtility.UrlEncode(s);
    37 38 
    39         #endregion 编码
      1 #region Cookie
      3           4          删除指定名称的Cookie
      5           6         <param name="name">Cookie名称  7         void DeleteCookie( name)
      8   9             HttpCookie cookie =  HttpCookie(name);
     10             cookie.Expires = DateTime.Now.AddYears(-1 11             HttpContext.Current.Response.AppendCookie(cookie);
     12  13 
     14          15          获得指定名称的Cookie值
     16          17          18          19         string GetCookie( 20  21             HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
     22             if (cookie !=  23                  cookie.Value;
     25             .Empty;
     26  27 
     28          29          获得指定名称的Cookie中特定键的值
     30          31          32          33          34         string name,1)"> 35  36             HttpCookie cookie = 37             null && cookie.HasKeys)
     38             {
     39                 string v = cookie[key];
     40                 if (v !=  41                      v;
     42             }
     43 
     44              45  47          48          设置指定名称的Cookie的值
     49          50          51         <param name="value"> 52         void SetCookie( 53  54             HttpCookie cookie = 55              56                 cookie.Value = 57              58                 cookie =  HttpCookie(name,value);
     59 
     60  61  63          64          65          66          67          68         <param name="expires">过期时间 69         string value,1)">double expires)
     70  71             HttpCookie cookie = 72             if (cookie ==  73                 cookie =  75             cookie.Value = 76             cookie.Expires = DateTime.Now.AddMinutes(expires);
     77  78  79 
     80          81          设置指定名称的Cookie特定键的值
     82          83          84          85          86          87  88             HttpCookie cookie = 89              90                 cookie =  91 
     92             cookie[key] = 93  94  95 
     96          97          98          99         100         101         102         103         104 105             HttpCookie cookie =106             107                 cookie = 109             cookie[key] =110             cookie.Expires =111 112 113 
    114         #endregion Cookie
      1         浏览器列表
      2         string[] _browserlist = new string[] { ie",chromemozillanetscapefirefoxoperakonqueror };
      3 
      4 #region 客户端信息
      5 
      7          是否是get请求
      8           9          10         bool IsGet()
     12             return HttpContext.Current.Request.HttpMethod == GET 13  是否是post请求
     IsPost()
     21             POST 22  23 
     24          25          是否是Ajax请求
     26          27          28          IsAjax()
     29  30             return HttpContext.Current.Request.Headers[X-Requested-With"] == XMLHttpRequest 34          获得查询字符串中的值
     35          36          37         <param name="defaultValue">默认值 38          39         string GetQueryString( defaultValue)
     40  41             string value = HttpContext.Current.Request.QueryString[key];
     42             if (!.IsNullOrWhiteSpace(value))
     43                  45                  defaultValue;
     46  47 
     52          53          54 return GetQueryString(key,1)">"" 56  57 
     58          59          60          61          62          64         int GetQueryInt(int 65  66              ConverterHelper.StringToInt(HttpContext.Current.Request.QueryString[key],defaultValue);
     67  69          70          71          72          73          74          75  76             return GetQueryInt(key,1)"> 79          获得表单中的值
     85         string GetFormString( 86  87              HttpContext.Current.Request.Form[key];
     88              89                  90              91                  92  93 
     94          95          99         100 101             return GetFormString(key,1)">102 103 
    104         105         106         107         108         109         110         int GetFormInt(112              ConverterHelper.StringToInt(HttpContext.Current.Request.Form[key],1)">115         116         117         118         119         120         122             return GetFormInt(key,1)">123 125         126          获得请求中的值
    127         128         129         130         131         string GetRequestString(132 133             if (HttpContext.Current.Request.Form[key] != 134                  GetFormString(key,1)">135             136                  GetQueryString(key,1)">137 139         140         141         142         143         144         146             147                  GetFormString(key);
    148             149                  GetQueryString(key);
    150 151 
    152         153         154         155         156         157         158         int GetRequestInt(160             161                  GetFormInt(key,1)">162             163                  GetQueryInt(key,1)">164 165 
    166         167         168         169         170         171         172 173             174                  GetFormInt(key);
    175             176                  GetQueryInt(key);
    179         180          获得上次请求的url
    181         182         183          GetUrlReferrer()
    184 185             Uri uri = HttpContext.Current.Request.UrlReferrer;
    186             if (uri == 187 188                 189 190              uri.ToString();
    191 192 
    193         194          获得请求的主机部分
    195         196         197          GetHost()
    198 199              HttpContext.Current.Request.Url.Host;
    200 201 
    202         203          获得请求的url
    204         205         206          GetUrl()
    207 208              HttpContext.Current.Request.Url.ToString();
    209 210 
    211         212          获得请求的原始url
    213         214         215          GetRawUrl()
    216 217              HttpContext.Current.Request.RawUrl;
    218 219 
    220         221          获得请求的ip
    222         223         224          GetIP()
    225 226             string ip = 227             if (HttpContext.Current.Request.ServerVariables[HTTP_VIA"] != 228                 ip = HttpContext.Current.Request.ServerVariables[HTTP_X_FORWARDED_FOR].ToString();
    229             230                 ip = HttpContext.Current.Request.ServerVariables[REMOTE_ADDR231 
    232             if (string.IsNullOrEmpty(ip) || !ValidateHelper.IsIP(ip))
    233                 ip = 127.0.0.1234              ip;
    235 236 
    237         238          获得请求的浏览器类型
    239         240         241          GetBrowserType()
    242 243             string type = HttpContext.Current.Request.Browser.Type;
    244             string.IsNullOrEmpty(type) || type == unknown245                 return 未知246 
    247              type.ToLower();
    248 249 
    250         251          获得请求的浏览器名称
    252         253         254          GetBrowserName()
    255 256             string name = HttpContext.Current.Request.Browser.Browser;
    257             string.IsNullOrEmpty(name) || name == 258                 259 
    260              name.ToLower();
    261 262 
    263         264          获得请求的浏览器版本
    265         266         267          GetBrowserVersion()
    268 269             string version = HttpContext.Current.Request.Browser.Version;
    270             string.IsNullOrEmpty(version) || version == 271                 272 
    273              version;
    274 275 
    276         277          获得请求客户端的操作系统类型
    278         279         280          GetOSType()
    281 282             string userAgent = HttpContext.Current.Request.UserAgent;
    283             if (userAgent == 284                 285 
    286             string type = 287             if (userAgent.Contains(NT 6.1))
    288                 type = Windows 7289             else NT 5.1290                 type = Windows XP291             NT 6.2292                 type = Windows 8293             android294                 type = Android295             iphone296                 type = IPhone297             Mac298                 type = 299             NT 6.0300                 type = Windows Vista301             NT 5.2302                 type = Windows 2003303             NT 5.0304                 type = Windows 2000305             98306                 type = Windows 98307             95308                 type = Windows 95309             Me310                 type = Windows Me311             NT 4312                 type = Windows NT4313             Unix314                 type = UNIX315             Linux316                 type = 317             SunOS318                 type = 319             320                 type = 321 
    322              type;
    323 324 
    325         326          获得请求客户端的操作系统名称
    327         328         329          GetOSName()
    330 331              HttpContext.Current.Request.Browser.Platform;
    332             .IsNullOrEmpty(name))
    333                 334 
    335              name;
    336 337 
    338         339          判断是否是浏览器请求
    340         341         342          IsBrowser()
    343 344              GetBrowserName();
    345             foreach (string item  _browserlist)
    346 347                  (name.Contains(item))
    348                     349 350             351 352 
    353         354          是否是移动设备请求
    355         356         357          IsMobile()
    358 359              (HttpContext.Current.Request.Browser.IsMobileDevice)
    360                 361 
    362             bool isTablet = 363             bool.TryParse(HttpContext.Current.Request.Browser[IsTablet"],1)">out isTablet) && isTablet)
    364                 365 
    366             367 368 
    369         370          判断是否是搜索引擎爬虫请求
    371         372         373          IsCrawler()
    374 375             bool result = HttpContext.Current.Request.Browser.Crawler;
    376             result)
    377 378                 string referrer = GetUrlReferrer();
    379                 if (referrer.Length > 380                 {
    381                      _searchenginelist)
    382                     {
    383                          (referrer.Contains(item))
    384                             385                     }
    386                 }
    387 388              result;
    389 390 
    391         #endregion 客户端信息

    ?

  • ConverterHelper 【类型转换帮助类】

    Json类型数据的转换是通过开源类库Json.Net来实现,利用反射将DataTable对象转换为List对象,字符串转换为其他常用类型

?

  1    2      类型转换助手
  3       4      ConverterHelper
  5     {
 利用反射和泛型
<param name="dt">DataTable 对象 10          11         static List<T> DataTableToList<T>(DataTable dt) where T : class,1)">()
 13              定义集合
 14             List<T> ts = new List<T>();
 15 
 16              获得此模型的类型
 17             Type type = typeof(T);
 18             定义一个临时变量
 19             string tempName =  20             遍历DataTable中所有的数据行
foreach (DataRow dr  dt.Rows)
 23                 T t =  T();
 24                  获得此模型的公共属性
 25                 PropertyInfo[] propertys = t.GetType().GetProperties();
 26                 遍历该对象的所有属性
 27                 foreach (PropertyInfo pi  propertys)
 28  29                     tempName = pi.Name;将属性名称赋值给临时变量
 30                                        检查DataTable是否包含此列(列名==对象的属性名)
 31                      (dt.Columns.Contains(tempName))
 32  33                         取值
 34                         object value = dr[tempName];
 35                         如果非空,则赋给对象的属性
 36                         if (value != DBNull.Value)
 37                             pi.SetValue(t,value,1)">对象添加到泛型集合中
 41                 ts.Add(t);
 ts;
 将object对象转换为Json数据
<param name="obj">object对象转换后的json字符串string ObjectToJson(object obj)
 54              JsonConvert.SerializeObject(obj);
 57          将Json对象转换为T对象
<typeparam name="T">对象的类型</typeparam>
<param name="jsonString">json对象字符串由字符串转换得到的T对象 63         static T JsonToObject<T>( jsonString)
 64  65             return JsonConvert.DeserializeObject<T>(jsonString);
 66  67 
 从字符串中获取数据
<param name="content">源字符串字符串中的值 73         string GetContent( content)
 74  75             return (String.IsNullOrEmpty(content) ?  : content);
 76  77 
 78          将int转换为bool类型
<param name="value"></param>
 83         bool ConvertIntToBool( 84  85             return (value > 0 ? true :  87 
 88         #region 转Int
 89 
 90          91          将string类型转换成int类型
 92          93         <param name="s">目标字符串 96         int StringToInt(string s,1)"> 97  98             .IsNullOrWhiteSpace(s))
 99 100                 101                 int.TryParse(s,1)">out result))
102                     103 105             106 107 
110         111         112         113         114 115             return StringToInt(s,1)">116 117 
 将object类型转换成int类型
120         121         目标对象122         123         124         int ObjectToInt(object o,1)">126             if (o != 127                  StringToInt(o.ToString(),1)">129             130 131 
132         133         134         135         136         137          o)
138 139             return ObjectToInt(o,1)">140 141 
142         #endregion 转Int
143 
#region 转Bool
145 
146         147          将string类型转换成bool类型
148         149         150         151         152         bool StringToBool(153 154             if (s.ToLower().Equals(false155                 156             true157                 159             160 161 
162         163         164         165         167         bool ToBool(168 169             return StringToBool(s,1)">170 171 
172         173          将object类型转换成bool类型
174         175         176         177         178         bool ObjectToBool(180             181                  StringToBool(o.ToString(),1)">183             185 
186         187         188         189         190         191         192 193             return ObjectToBool(o,1)">194 195 
196         #endregion 转Bool
197 
198         #region 转DateTime
199 
200         201          将string类型转换成datetime类型
static DateTime StringToDateTime( s,DateTime defaultValue)
210                 DateTime result;
211                 if (DateTime.TryParse(s,1)">212                     213 214             215 216 
217         218         219         222         223 224              StringToDateTime(s,DateTime.Now);
226 
227         228          将object类型转换成datetime类型
229         230         231         232         233         static DateTime ObjectToDateTime( o,1)">234 235             236                  StringToDateTime(o.ToString(),1)">237 
238             239 240 
241         242         243         244         245         246         247 248              ObjectToDateTime(o,1)">249 250 
251         #endregion 转DateTime
252 
253         #region 转Decimal
254 
255         256          将string类型转换成decimal类型
257         258         259         260         261         decimal StringToDecimal(decimal262 263             264 265                 266                 decimal.TryParse(s,1)">267                     269 
271 273         274         275         278         279 280              StringToDecimal(s,0m);
282 
283         284          将object类型转换成decimal类型
285         286         287         288         289         decimal ObjectToDecimal(290 292                  StringToDecimal(o.ToString(),1)">293 
294             295 296 
297         298         299         300         301         302         303 304              ObjectToDecimal(o,1)">305 306 
307         #endregion 转Decimal
308     }

?

7.项目架构搭建之Models搭建

????参考 这里 了解 EF CodeFirst,首先对EF类库进行引用,由于我的应用的使用的是SQLServer数据库,所以需要对EntityFramework.SqlServer进行引用,如果不引用子在进行数据库相关操作时会出错,错误如下:

The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices,EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

?

  1. 添加类库引用
  2. 创建Entity

    创建一个类,继承DbContext类,并在他的构造函数中设置连接字符串或者构造函数中传递配置文件中ConnectionStrings的name

  3. 创建数据模型models

    创建Web应用中用到的Model对应数据库中的表,ViewModel另外设置,这里的models对应数据库的数据表,User示例:

  4. 启用数据迁移 EnableMigration
    1. 打开 Package Manager Console

    2. 执行命令 "Enable-Migrations",如果这个项目中有两个或两个以上的继承DbContext类的Entity,需要制定Context的名称,不然会提示有多个Context。
    3. 执行命令之后会生成一个 Migrations文件夹,文件夹下有一个Configuration文件,打开文件修改构造函数,设置 AutomaticMigrationsEnabled = true;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读