适用于app.config与web.config的ConfigUtil读写工具类 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类) 基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

时间:2023-12-10 09:16:08

适用于app.config与web.config的ConfigUtil读写工具类

之前文章:《两种读写配置文件的方案(app.config与web.config通用)》,现在重新整理一个更完善的版本,增加批量读写以及指定配置文件路径,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.IO;
namespace Zuowj.Utils
{
    /// <summary>
    /// 配置工具类
    /// Author:左文俊
    /// Date:2018/1/27
    public static class ConfigUtil
    {
        /// <summary>
        /// 获取管理配置文件对象Configuration
        /// </summary>
        /// <param name="configPath">指定要管理的配置文件路径,如果为空或不存在,则管理程序集默认的配置文件路径</param>
        /// <returns></returns>
        private static Configuration GetConfiguration(string configPath = null)
        {
            if (!string.IsNullOrEmpty(configPath) && File.Exists(configPath))
            {
                ExeConfigurationFileMap map = new ExeConfigurationFileMap();
                map.ExeConfigFilename = configPath;
                return ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            }
            else
            {
                return ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            }
        }
        /// <summary>
        /// 获取指定配置文件+配置名称的配置项的值
        /// </summary>
        public static string GetAppSettingValue(string key, string defaultValue = nullstring configPath = null)
        {
            var config = GetConfiguration(configPath);
            var appSetting = config.AppSettings.Settings[key];
            return appSetting.Value;
        }
        /// <summary>
        /// 设置配置值(存在则更新,不存在则新增)
        /// </summary>
        public static void SetAppSettingValue(string key, string value, string configPath = null)
        {
            var config = GetConfiguration(configPath);
            var setting = config.AppSettings.Settings[key];
            if (setting == null)
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                setting.Value = value;
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
        /// <summary>
        /// 删除配置值
        /// </summary>
        public static void RemoveAppSetting(string key, string configPath = null)
        {
            var config = GetConfiguration(configPath);
            config.AppSettings.Settings.Remove(key);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
        /// <summary>
        /// 设置多个配置值(存在则更新,不存在则新增)
        /// </summary>
        public static void SetAppSettingValues(IEnumerable<KeyValuePair<stringstring>> settingValues, string configPath = null)
        {
            var config = GetConfiguration(configPath);
            foreach (var item in settingValues)
            {
                var setting = config.AppSettings.Settings[item.Key];
                if (setting == null)
                {
                    config.AppSettings.Settings.Add(item.Key, item.Value);
                }
                else
                {
                    setting.Value = item.Value;
                }
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
        /// <summary>
        /// 获取所有配置值
        /// </summary>
        public static Dictionary<stringstring> GetAppSettingValues(string configPath = null)
        {
            Dictionary<stringstring> settingDic = new Dictionary<stringstring>();
            var config = GetConfiguration(configPath);
            var settings = config.AppSettings.Settings;
            foreach (string key in settings.AllKeys)
            {
                settingDic[key] = settings[key].ToString();
            }
            return settingDic;
        }
        /// <summary>
        /// 删除多个配置值
        /// </summary>
        public static void RemoveAppSettings(string configPath = nullparams string[] keys)
        {
            var config = GetConfiguration(configPath);
            if (keys != null)
            {
                foreach (string key in keys)
                {
                    config.AppSettings.Settings.Remove(key);
                }
            }
            else
            {
                config.AppSettings.Settings.Clear();
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
        /// <summary>
        /// 获取连接字符串
        /// </summary>
        public static string GetConnectionString(string name, string defaultconnStr = nullstring configPath = null)
        {
            var config = GetConfiguration(configPath);
            var connStrSettings = config.ConnectionStrings.ConnectionStrings[name];
            if (connStrSettings == null)
            {
                return defaultconnStr;
            }
            return connStrSettings.ConnectionString;
        }
        /// <summary>
        /// 获取指定配置文件+连接名称的连接字符串配置项
        /// </summary>
        public static ConnectionStringSettings GetConnectionStringSetting(string name, string configPath = null)
        {
            var config = GetConfiguration(configPath);
            var connStrSettings = config.ConnectionStrings.ConnectionStrings[name];
            return connStrSettings;
        }
        /// <summary>
        /// 设置连接字符串的值(存在则更新,不存在则新增)
        /// </summary>
        public static void SetConnectionString(string name, string connstr, string provider, string configPath = null)
        {
            var config = GetConfiguration(configPath);
            ConnectionStringSettings connStrSettings = config.ConnectionStrings.ConnectionStrings[name];
            if (connStrSettings != null)
            {
                connStrSettings.ConnectionString = connstr;
                connStrSettings.ProviderName = provider;
            }
            else
            {
                connStrSettings = new ConnectionStringSettings(name, connstr, provider);
                config.ConnectionStrings.ConnectionStrings.Add(connStrSettings);
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("connectionStrings");
        }
        /// <summary>
        /// 删除连接字符串配置项
        /// </summary>
        public static void RemoveConnectionString(string name, string configPath = null)
        {
            var config = GetConfiguration(configPath);
            config.ConnectionStrings.ConnectionStrings.Remove(name);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("connectionStrings");
        }
        /// <summary>
        /// 获取所有的连接字符串配置项
        /// </summary>
        public static Dictionary<string, ConnectionStringSettings> GetConnectionStringSettings(string configPath = null)
        {
            var config = GetConfiguration(configPath);
            var connStrSettingDic = new Dictionary<string, ConnectionStringSettings>();
            var connStrSettings = ConfigurationManager.ConnectionStrings;
            foreach (ConnectionStringSettings item in connStrSettings)
            {
                connStrSettingDic[item.Name] = item;
            }
            return connStrSettingDic;
        }
        /// <summary>
        /// 设置多个连接字符串的值(存在则更新,不存在则新增)
        /// </summary>
        public static void SetConnectionStrings(IEnumerable<ConnectionStringSettings> connStrSettings, string configPath = null)
        {
            var config = GetConfiguration(configPath);
            foreach (var item in connStrSettings)
            {
                ConnectionStringSettings connStrSetting = config.ConnectionStrings.ConnectionStrings[item.Name];
                if (connStrSetting != null)
                {
                    connStrSetting.ConnectionString = item.ConnectionString;
                    connStrSetting.ProviderName = item.ProviderName;
                }
                else
                {
                    config.ConnectionStrings.ConnectionStrings.Add(item);
                }
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("connectionStrings");
        }
        /// <summary>
        /// 删除多个连接字符串配置项
        /// </summary>
        public static void RemoveConnectionStrings(string configPath = nullparams string[] names)
        {
            var config = GetConfiguration(configPath);
            if (names != null)
            {
                foreach (string name in names)
                {
                    config.ConnectionStrings.ConnectionStrings.Remove(name);
                }
            }
            else
            {
                config.ConnectionStrings.ConnectionStrings.Clear();
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("connectionStrings");
        }
    }
}

  

基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)

近期工作中有使用到 MongoDb作为日志持久化对象,需要实现对MongoDb的增、删、改、查,但由于MongoDb的版本比较新,是2.4以上版本的,网上已有的一些MongoDb Helper类都是基于之前MongoDb旧的版本,无法适用于新版本的MongoDb,故我基于MongoDb官方C#驱动重新封装了MongoDbCsharpHelper类(CRUD类),完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
using MongoDB;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Web;
namespace Zuowj.Utils
{
    /// <summary>
    /// MongoDbCsharpHelper:MongoDb基于C#语言操作帮助类
    /// Author:Zuowenjun
    /// Date:2017/11/16
    /// </summary>
    public class MongoDbCsharpHelper
    {
        private readonly string connectionString = null;
        private readonly string databaseName = null;
        private MongoDB.Driver.IMongoDatabase database = null;
        private readonly bool autoCreateDb = false;
        private readonly bool autoCreateCollection = false;
        static MongoDbCsharpHelper()
        {
            BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;
        }
        public MongoDbCsharpHelper(string mongoConnStr, string dbName, bool autoCreateDb = falsebool autoCreateCollection = false)
        {
            this.connectionString = mongoConnStr;
            this.databaseName = dbName;
            this.autoCreateDb = autoCreateDb;
            this.autoCreateCollection = autoCreateCollection;
        }
        #region 私有方法
        private MongoClient CreateMongoClient()
        {
            return new MongoClient(connectionString);
        }
        private MongoDB.Driver.IMongoDatabase GetMongoDatabase()
        {
            if (database == null)
            {
                var client = CreateMongoClient();
                if (!DatabaseExists(client, databaseName) && !autoCreateDb)
                {
                    throw new KeyNotFoundException("此MongoDB名称不存在:" + databaseName);
                }
                database = CreateMongoClient().GetDatabase(databaseName);
            }
            return database;
        }
        private bool DatabaseExists(MongoClient client, string dbName)
        {
            try
            {
                var dbNames = client.ListDatabases().ToList().Select(db => db.GetValue("name").AsString);
                return dbNames.Contains(dbName);
            }
            catch //如果连接的账号不能枚举出所有DB会报错,则默认为true
            {
                return true;
            }
        }
        private bool CollectionExists(IMongoDatabase database, string collectionName)
        {
            var options = new ListCollectionsOptions
            {
                Filter = Builders<BsonDocument>.Filter.Eq("name", collectionName)
            };
            return database.ListCollections(options).ToEnumerable().Any();
        }
        private MongoDB.Driver.IMongoCollection<TDoc> GetMongoCollection<TDoc>(string name, MongoCollectionSettings settings = null)
        {
            var mongoDatabase = GetMongoDatabase();
            if (!CollectionExists(mongoDatabase, name) && !autoCreateCollection)
            {
                throw new KeyNotFoundException("此Collection名称不存在:" + name);
            }
            return mongoDatabase.GetCollection<TDoc>(name, settings);
        }
        private List<UpdateDefinition<TDoc>> BuildUpdateDefinition<TDoc>(object doc, string parent)
        {
            var updateList = new List<UpdateDefinition<TDoc>>();
            foreach (var property in typeof(TDoc).GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                var key = parent == null ? property.Name : string.Format("{0}.{1}", parent, property.Name);
                //非空的复杂类型
                if ((property.PropertyType.IsClass || property.PropertyType.IsInterface) && property.PropertyType != typeof(string) && property.GetValue(doc) != null)
                {
                    if (typeof(IList).IsAssignableFrom(property.PropertyType))
                    {
                        #region 集合类型
                        int i = 0;
                        var subObj = property.GetValue(doc);
                        foreach (var item in subObj as IList)
                        {
                            if (item.GetType().IsClass || item.GetType().IsInterface)
                            {
                                updateList.AddRange(BuildUpdateDefinition<TDoc>(doc, string.Format("{0}.{1}", key, i)));
                            }
                            else
                            {
                                updateList.Add(Builders<TDoc>.Update.Set(string.Format("{0}.{1}", key, i), item));
                            }
                            i++;
                        }
                        #endregion
                    }
                    else
                    {
                        #region 实体类型
                        //复杂类型,导航属性,类对象和集合对象
                        var subObj = property.GetValue(doc);
                        foreach (var sub in property.PropertyType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                        {
                            updateList.Add(Builders<TDoc>.Update.Set(string.Format("{0}.{1}", key, sub.Name), sub.GetValue(subObj)));
                        }
                        #endregion
                    }
                }
                else //简单类型
                {
                    updateList.Add(Builders<TDoc>.Update.Set(key, property.GetValue(doc)));
                }
            }
            return updateList;
        }
        private void CreateIndex<TDoc>(IMongoCollection<TDoc> col, string[] indexFields, CreateIndexOptions options = null)
        {
            if (indexFields == null)
            {
                return;
            }
            var indexKeys = Builders<TDoc>.IndexKeys;
            IndexKeysDefinition<TDoc> keys = null;
            if (indexFields.Length > 0)
            {
                keys = indexKeys.Descending(indexFields[0]);
            }
            for (var i = 1; i < indexFields.Length; i++)
            {
                var strIndex = indexFields[i];
                keys = keys.Descending(strIndex);
            }
            if (keys != null)
            {
                col.Indexes.CreateOne(keys, options);
            }
        }
        #endregion
        public void CreateCollectionIndex<TDoc>(string collectionName, string[] indexFields, CreateIndexOptions options = null)
        {
            CreateIndex(GetMongoCollection<TDoc>(collectionName), indexFields, options);
        }
        public void CreateCollection<TDoc>(string[] indexFields = null, CreateIndexOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            CreateCollection<TDoc>(collectionName, indexFields, options);
        }
        public void CreateCollection<TDoc>(string collectionName, string[] indexFields = null, CreateIndexOptions options = null)
        {
            var mongoDatabase = GetMongoDatabase();
            mongoDatabase.CreateCollection(collectionName);
            CreateIndex(GetMongoCollection<TDoc>(collectionName), indexFields, options);
        }
        public List<TDoc> Find<TDoc>(Expression<Func<TDoc, bool>> filter, FindOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            return Find<TDoc>(collectionName, filter, options);
        }
        public List<TDoc> Find<TDoc>(string collectionName, Expression<Func<TDoc, bool>> filter, FindOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            return colleciton.Find(filter, options).ToList();
        }
        public List<TDoc> FindByPage<TDoc, TResult>(Expression<Func<TDoc, bool>> filter, Expression<Func<TDoc, TResult>> keySelector, int pageIndex, int pageSize, out int rsCount)
        {
            string collectionName = typeof(TDoc).Name;
            return FindByPage<TDoc, TResult>(collectionName, filter, keySelector, pageIndex, pageSize, out rsCount);
        }
        public List<TDoc> FindByPage<TDoc, TResult>(string collectionName, Expression<Func<TDoc, bool>> filter, Expression<Func<TDoc, TResult>> keySelector, int pageIndex, int pageSize, out int rsCount)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            rsCount = colleciton.AsQueryable().Where(filter).Count();
            int pageCount = rsCount / pageSize + ((rsCount % pageSize) > 0 ? 1 : 0);
            if (pageIndex > pageCount) pageIndex = pageCount;
            if (pageIndex <= 0) pageIndex = 1;
            return colleciton.AsQueryable(new AggregateOptions { AllowDiskUse = true }).Where(filter).OrderByDescending(keySelector).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }
        public void Insert<TDoc>(TDoc doc, InsertOneOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            Insert<TDoc>(collectionName, doc, options);
        }
        public void Insert<TDoc>(string collectionName, TDoc doc, InsertOneOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            colleciton.InsertOne(doc, options);
        }
        public void InsertMany<TDoc>(IEnumerable<TDoc> docs, InsertManyOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            InsertMany<TDoc>(collectionName, docs, options);
        }
        public void InsertMany<TDoc>(string collectionName, IEnumerable<TDoc> docs, InsertManyOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            colleciton.InsertMany(docs, options);
        }
        public void Update<TDoc>(TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc, null);
            colleciton.UpdateOne(filter, Builders<TDoc>.Update.Combine(updateList), options);
        }
        public void Update<TDoc>(string collectionName, TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc, null);
            colleciton.UpdateOne(filter, Builders<TDoc>.Update.Combine(updateList), options);
        }
        public void Update<TDoc>(TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateDefinition<TDoc> updateFields, UpdateOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            Update<TDoc>(collectionName, doc, filter, updateFields, options);
        }
        public void Update<TDoc>(string collectionName, TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateDefinition<TDoc> updateFields, UpdateOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            colleciton.UpdateOne(filter, updateFields, options);
        }
        public void UpdateMany<TDoc>(TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            UpdateMany<TDoc>(collectionName, doc, filter, options);
        }
        public void UpdateMany<TDoc>(string collectionName, TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc, null);
            colleciton.UpdateMany(filter, Builders<TDoc>.Update.Combine(updateList), options);
        }
        public void Delete<TDoc>(Expression<Func<TDoc, bool>> filter, DeleteOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            Delete<TDoc>(collectionName, filter, options);
        }
        public void Delete<TDoc>(string collectionName, Expression<Func<TDoc, bool>> filter, DeleteOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            colleciton.DeleteOne(filter, options);
        }
        public void DeleteMany<TDoc>(Expression<Func<TDoc, bool>> filter, DeleteOptions options = null)
        {
            string collectionName = typeof(TDoc).Name;
            DeleteMany<TDoc>(collectionName, filter, options);
        }
        public void DeleteMany<TDoc>(string collectionName, Expression<Func<TDoc, bool>> filter, DeleteOptions options = null)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            colleciton.DeleteMany(filter, options);
        }
        public void ClearCollection<TDoc>(string collectionName)
        {
            var colleciton = GetMongoCollection<TDoc>(collectionName);
            var inddexs = colleciton.Indexes.List();
            List<IEnumerable<BsonDocument>> docIndexs = new List<IEnumerable<BsonDocument>>();
            while (inddexs.MoveNext())
            {
                docIndexs.Add(inddexs.Current);
            }
            var mongoDatabase = GetMongoDatabase();
            mongoDatabase.DropCollection(collectionName);
            if (!CollectionExists(mongoDatabase, collectionName))
            {
                CreateCollection<TDoc>(collectionName);
            }
            if (docIndexs.Count > 0)
            {
                colleciton = mongoDatabase.GetCollection<TDoc>(collectionName);
                foreach (var index in docIndexs)
                {
                    foreach (IndexKeysDefinition<TDoc> indexItem in index)
                    {
                        try
                        {
                            colleciton.Indexes.CreateOne(indexItem);
                        }
                        catch
                        { }
                    }
                }
            }
        }
    }
}

对上述代码中几个特别的点进行简要说明:

1.由于MongoClient.GetDatabase 获取DB、MongoClient.GetCollection<TDoc> 获取文档(也可称为表)的方法 都有一个特点,即:如果指定的DB名称、Collection名称不存在,则会直接创建,但有的时候可能是因为DB名称、Collection名称写错了导致误创建了的DB或Collection,那就引起不必要的麻烦,故在MongoDbCsharpHelper类类内部封装了两个私有的方法:DatabaseExists(判断DB是否存在,如是连接的账号没有检索DB的权限可能会报错,故代码中加了直接返回true)、CollectionExists(判断Collection是否存在);

2.每个CRUD方法,我都分别重载了两个方法,一个是无需指定Collection名称,一个是需要指定Collection名称,为什么这么做呢?原因很简单,因为有时Collection的结构是相同的但又是不同的Collection,这时TDoc是同一个实体类,但collectionName却是不同的;

3.分页查询的时候如果Collection的数据量比较大,那么就会报类似错误:exception: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. Aborting operation. Pass allowDiskUse:true,根据报错提示,我们在查询大数据量时增加AggregateOptions对象,如: colleciton.AsQueryable(new AggregateOptions { AllowDiskUse = true })

4.ClearCollection清除Collection的所有数据,如果Collection的数据量非常大,那么直接使用colleciton.DeleteMany可能需要很久,有没有类似SQL SERVER 的truncate table的方法呢?经过多方论证,很遗憾并没有找到同类功能的方法,只有DropCollection方法,而这个DropCollection方法是直接删除Collection,当然包括Collection的所有数据,效率也非常高,但是由于是Drop,Collection就不存在了,如果再访问有可能会报Collection不存在的错误,那有没有好的办法解决了,当然有,那就是先DropCollection 然后再CreateCollection,最后别忘了把原有的索引插入到新创建的Collection中,这样就实现了truncate 初始化表的作用,当然在创建索引的时候,有的时候可能报报错(如:_id),因为_id默认就会被创建索引,再创建可能就会报错,故colleciton.Indexes.CreateOne外我加了try catch,如果报错则忽略。

5.CreateCollection(创建集合)、CreateCollectionIndex(创建集合索引)因为有的时候我们需要明确的去创建一个Collection或对已有的Collection创建索引,如果通过shell命令会非常不方便,故在此封装了一下。

使用示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var mongoDbHelper = new MongoDbCsharpHelper("MongoDbConnectionString""LogDB");
mongoDbHelper.CreateCollection<SysLogInfo>("SysLog1",new[]{"LogDT"});
mongoDbHelper.Find<SysLogInfo>("SysLog1", t => t.Level == "Info");
int rsCount=0;
mongoDbHelper.FindByPage<SysLogInfo, SysLogInfo>("SysLog1",t=>t.Level=="Info",t=>t,1,20,out rsCount);
mongoDbHelper.Insert<SysLogInfo>("SysLog1",new SysLogInfo { LogDT = DateTime.Now, Level = "Info", Msg = "测试消息" });
mongoDbHelper.Update<SysLogInfo>("SysLog1",new SysLogInfo { LogDT = DateTime.Now, Level = "Error", Msg = "测试消息2" },t => t.LogDT==new DateTime(1900,1,1));
mongoDbHelper.Delete<SysLogInfo>(t => t.Level == "Info");
mongoDbHelper.ClearCollection<SysLogInfo>("SysLog1");

基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD)

一些小的C/S项目(winform、WPF等),因需要访问操作数据库,但又不能把DB连接配置在客户端上,原因有很多,可能是DB连接无法直接访问,或客户端不想安装各种DB访问组件,或DB连接不想暴露在客户端(即使加密连接字符串仍有可能被破解的情况),总之都是出于安全考虑,同时因项目小,也无需采用分布式架构来将业务操作封装到服务端,但又想保证客户端业务的正常处理,这时我们就可以利用ASP.NET WEB API框架开发一个简单的提供对数据库的直接操作(CRUD)框架,简称为:分布式数据访问中间层。

实现方案很简单,就是利用ASP.NET WEB API框架编写于一个DataController,然后在DataController分别实现CRUD相关的公开ACTION方法即可,具体实现代码如下:(因为逻辑简单,一看就懂,故下面不再详细说明逻辑,文末会有一些总结)

ASP.NET WEB API服务端相关核心代码:

1.DataController代码:

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
    [SqlInjectionFilter]
    [Authorize]
    public class DataController : ApiController
    {

        [AllowAnonymous]
        [HttpPost]
        public ApiResultInfo Login([FromBody]string[] loginInfo)
        {
            ApiResultInfo loginResult = null;
            try
            {
                if (loginInfo == null || loginInfo.Length != 4)
                {
                    throw new Exception("登录信息不全。");
                }

                using (var da = BaseUtil.CreateDataAccess())
                {
                    if (用户名及密码判断逻辑)
                    {
                        throw new Exception("登录名或密码错误。");
                    }
                    else
                    {
                        string token = Guid.NewGuid().ToString("N");
                        HttpRuntime.Cache.Insert(Constants.CacheKey_SessionTokenPrefix + token, loginInfo[0], null, Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1));

                        //登录成功后需要处理的逻辑

                        loginResult = ApiResultInfo.BuildOKResult(token);
                    }
                }
            }
            catch (Exception ex)
            {
                LogUitl.Error(ex, "Api.Data.Login", BaseUtil.SerializeToJson(loginInfo));
                loginResult = ApiResultInfo.BuildErrResult("LoginErr", ex.Message);
            }

            return loginResult;
        }

        [HttpPost]
        public ApiResultInfo LogOut([FromBody] string token)
        {
            try
            {
                if (!string.IsNullOrEmpty(token))
                {
                    if (HttpRuntime.Cache[Constants.CacheKey_SessionTokenPrefix + token] != null)
                    {
                        HttpRuntime.Cache.Remove(token);
                    }

                    using (var da = BaseUtil.CreateDataAccess())
                    {
                        //登出后需要处理的逻辑
                    }
                }
            }
            catch
            { }

            return ApiResultInfo.BuildOKResult();
        }

        [HttpPost]
        public ApiResultInfo GetValue([FromBody]SqlCmdInfo sqlCmd)
        {
            using (var da = BaseUtil.CreateDataAccess())
            {
                var result = da.ExecuteScalar<string>(sqlCmd.SqlCmdText, sqlCmd.GetCommandType(), sqlCmd.Parameters.TryToArray());
                return ApiResultInfo.BuildOKResult(result);
            }

        }

        [Compression]
        [HttpPost]
        public ApiResultInfo GetDataSet([FromBody]SqlCmdInfo sqlCmd)
        {
            using (var da = BaseUtil.CreateDataAccess())
            {
                var ds = da.ExecuteDataSet(sqlCmd.SqlCmdText, sqlCmd.GetCommandType(), sqlCmd.Parameters.TryToArray());
                return ApiResultInfo.BuildOKResult(ds);
            }
        }

        [Compression]
        [HttpPost]
        public ApiResultInfo GetDataTable([FromBody]SqlCmdInfo sqlCmd)
        {
            using (var da = BaseUtil.CreateDataAccess())
            {
                var table = da.ExecuteDataTable(sqlCmd.SqlCmdText, sqlCmd.GetCommandType(), sqlCmd.Parameters.TryToArray());
                return ApiResultInfo.BuildOKResult(table);
            }
        }

        [HttpPost]
        public ApiResultInfo ExecuteCommand([FromBody]SqlCmdInfo sqlCmd)
        {
            using (var da = BaseUtil.CreateDataAccess())
            {
                int result = da.ExecuteCommand(sqlCmd.SqlCmdText, sqlCmd.GetCommandType(), sqlCmd.Parameters.TryToArray());
                return ApiResultInfo.BuildOKResult(result);
            }
        }

        [HttpPost]
        public ApiResultInfo BatchExecuteCommand([FromBody] IEnumerable<SqlCmdInfo> sqlCmds)
        {
            using (var da = BaseUtil.CreateDataAccess())
            {
                int execCount = 0;
                da.UseTransaction();
                foreach (var sqlCmd in sqlCmds)
                {
                    execCount += da.ExecuteCommand(sqlCmd.SqlCmdText, sqlCmd.GetCommandType(), sqlCmd.Parameters.TryToArray());
                }
                da.Commit();
                return new ApiResultInfo(execCount > 0);
            }
        }

        [HttpPost]
        public async Task<ApiResultInfo> ExecuteCommandAsync([FromBody]SqlCmdInfo sqlCmd)
        {
            return await Task.Factory.StartNew((arg) =>
             {
                 var sqlCmdObj = arg as SqlCmdInfo;
                 string connName = BaseUtil.GetDbConnectionName(sqlCmdObj.DbType);
                 using (var da = BaseUtil.CreateDataAccess(connName))
                 {
                     try
                     {
                         int result = da.ExecuteCommand(sqlCmdObj.SqlCmdText, sqlCmdObj.GetCommandType(), sqlCmdObj.Parameters.TryToArray());
                         return ApiResultInfo.BuildOKResult(result);
                     }
                     catch (Exception ex)
                     {
                         LogUitl.Error(ex, "Api.Data.ExecuteCommandAsync", BaseUtil.SerializeToJson(sqlCmdObj));

                         return ApiResultInfo.BuildErrResult("ExecuteCommandAsyncErr", ex.Message,
                                new Dictionary<string, object> { { "StackTrace", ex.StackTrace } });
                     }
                 }
             }, sqlCmd);
        }

        [HttpPost]
        public IHttpActionResult SaveLog([FromBody]string[] logInfo)
        {
            if (logInfo == null || logInfo.Length < 3)
            {
                return Ok();
            }

            string[] saveLogInfo = new string[7];
            for (int i = 1; i < logInfo.Length; i++)
            {
                if (saveLogInfo.Length > i + 1)
                {
                    saveLogInfo[i] = logInfo[i];
                }
            }

            switch (saveLogInfo[0].ToUpperInvariant())
            {
                case "ERR":
                    {
                        LogUitl.Error(saveLogInfo[1], saveLogInfo[2], saveLogInfo[3], saveLogInfo[4], saveLogInfo[5], saveLogInfo[6]);
                        break;
                    }
                case "WARN":
                    {
                        LogUitl.Warn(saveLogInfo[1], saveLogInfo[2], saveLogInfo[3], saveLogInfo[4], saveLogInfo[5], saveLogInfo[6]);
                        break;
                    }
                case "INFO":
                    {
                        LogUitl.Info(saveLogInfo[1], saveLogInfo[2], saveLogInfo[3], saveLogInfo[4], saveLogInfo[5], saveLogInfo[6]);
                        break;
                    }
            }

            return Ok();

        }

    }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

2.SqlInjectionFilterAttribute (防止SQL注入、危险关键字攻击过滤器)

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class SqlInjectionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (actionContext.ActionArguments.ContainsKey("sqlCmd"))
            {
                var sqlCmd = actionContext.ActionArguments["sqlCmd"] as SqlCmdInfo;
                if (BaseUtil.IsIncludeDangerSql(sqlCmd.SqlCmdText))
                {
                    throw new Exception("存在SQL注入风险,禁止操作!");
                }
            }

            base.OnActionExecuting(actionContext);
        }
    }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

IsIncludeDangerSql:判断是否包含危险关键字

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
        /// <summary>
        /// 判断是否包含危险的SQL关键词
        /// </summary>
        /// <param name="sqlCmdText"></param>
        /// <returns>包含返回true,否则false</returns>
        public static bool IsIncludeDangerSql(string sqlCmdText)
        {
            if (string.IsNullOrWhiteSpace(sqlCmdText)) return false;

            sqlCmdText = sqlCmdText.Replace("[", " ").Replace("]", " ");

            //string dangerSqlObjs = @"sys\.columns|sys\.tables|sys\.views|sys\.objects|sys\.procedures|sys\.indexes|INFORMATION_SCHEMA\.TABLES|INFORMATION_SCHEMA\.VIEWS|INFORMATION_SCHEMA\.COLUMNS|GRANT|DENY|SP_HELP|SP_HELPTEXT";
            //dangerSqlObjs += @"|object_id|syscolumns|sysobjects|sysindexes|drop\s+\w+|alter\s+\w+|create\s+\w+";

            string dangerSqlObjs = @"sys\.\w+|INFORMATION_SCHEMA\.\w+|GRANT|DENY|SP_HELP|SP_HELPTEXT|sp_executesql";
            dangerSqlObjs += @"|object_id|syscolumns|sysobjects|sysindexes|exec\s+\(.+\)|(create|drop|alter)\s+(database|table|index|procedure|view|trigger)\s+\w+(?!#)";

            string patternStr = string.Format(@"(^|\s|,|\.)({0})(\s|,|\(|;|$)", dangerSqlObjs);
            bool mathed = Regex.IsMatch(sqlCmdText, patternStr, RegexOptions.IgnoreCase);
            if (mathed)
            {
                //TODO:记录到危险请求表中,以便后续追查
                LogUitl.Warn("检测到包含危险的SQL关键词语句:" + sqlCmdText, "IsIncludeDangerSql");
            }

            return mathed;
        }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

3.SqlCmdInfo (ACTION参数对象,SQL命令信息类)

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
    [Serializable]
    public class SqlCmdInfo
    {
        public string SqlCmdText { get; set; }

        public ArrayList Parameters { get; set; }

        public bool IsSPCmdType { get; set; }

        public int DbType { get; set; }

        public CommandType GetCommandType()
        {
            return IsSPCmdType ? CommandType.StoredProcedure : CommandType.Text;
        }
    }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

4.CompressionAttribute(压缩返回内容过滤器,当返回的是大量数据时,可以标记该过滤器,以便提高响应速度)

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
    /// <summary>
    /// 压缩返回信息
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class CompressionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var content = actionExecutedContext.Response.Content;

            #region 根据请求是否压缩,暂时不用
            ////var acceptEncoding = actionExecutedContext.Request.Headers.AcceptEncoding.
            ////    Where(x => x.Value == "gzip" || x.Value == "deflate").ToList();
            ////if (acceptEncoding.HasItem() && content != null && actionExecutedContext.Request.Method != HttpMethod.Options)
            ////{
            ////    var first = acceptEncoding.FirstOrDefault();
            ////    if (first != null)
            ////    {
            ////        var bytes = content.ReadAsByteArrayAsync().Result;
            ////        switch (first.Value)
            ////        {
            ////            case "gzip":
            ////                actionExecutedContext.Response.Content = new ByteArrayContent(CompressionHelper.GZipBytes(bytes));
            ////                actionExecutedContext.Response.Content.Headers.Add("Content-Encoding", "gzip");
            ////                break;
            ////            case "deflate":
            ////                actionExecutedContext.Response.Content = new ByteArrayContent(CompressionHelper.DeflateBytes(bytes));
            ////                actionExecutedContext.Response.Content.Headers.Add("Content-encoding", "deflate");
            ////                break;
            ////        }
            ////    }
            ////}

            #endregion

            //只要使用了CompressionAttribute,则默认使用GZIP压缩
            var bytes = content.ReadAsByteArrayAsync().Result;
            actionExecutedContext.Response.Content = new ByteArrayContent(CompressionHelper.GZipBytes(bytes));
            actionExecutedContext.Response.Content.Headers.Add("Content-Encoding", "gzip");

            base.OnActionExecuted(actionExecutedContext);
        }
    }
    /// <summary>
    /// 压缩帮助类
    /// </summary>
    internal static class CompressionHelper
    {
        public static byte[] DeflateBytes(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
            {
                return null;
            }
            using (var output = new MemoryStream())
            {
                using (var compressor = new DeflateStream(output, CompressionMode.Compress, false))
                {
                    compressor.Write(bytes, 0, bytes.Length);
                }
                return output.ToArray();
            }
        }

        public static byte[] GZipBytes(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
            {
                return null;
            }
            using (var output = new MemoryStream())
            {
                using (var compressor = new GZipStream(output, CompressionMode.Compress, false))
                {
                    compressor.Write(bytes, 0, bytes.Length);
                }
                return output.ToArray();
            }
        }
    }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

5.RequestAuthenticationHandler (验证请求合法性处理管道(包含请求内容解密),即:未正确登录则不能调API操作数据库)

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
    public class RequestAuthenticationHandler : DelegatingHandler
    {
        private const string rsaPrivateKey = "私钥字符串";
        protected async override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            try
            {
                //验证TOKEN
                HttpRequestHeaders headers = request.Headers;
                IEnumerable<string> tokenHeaders = null;
                if (headers.TryGetValues("AccessToken", out tokenHeaders) && tokenHeaders.Any())
                {

                    string loginID = TokenVerification(tokenHeaders.ElementAt(0));

                    if (!string.IsNullOrEmpty(loginID))
                    {
                        var principal = new GenericPrincipal(new GenericIdentity(loginID, "token"), null);
                        Thread.CurrentPrincipal = principal;
                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.User = principal;
                        }
                    }
                }

                IEnumerable<string> encryptHeaders=null;
                if (headers.TryGetValues("Encryption", out encryptHeaders) && encryptHeaders.Any())
                {
                    if (encryptHeaders.ElementAt(0) == "1")
                    {
                        //私钥解密请求体内容
                        var originContent = request.Content;
                        string requestData = await request.Content.ReadAsStringAsync();

                        string deContentStr = EncryptUtility.RSADecrypt(rsaPrivateKey, requestData);
                        request.Content = new StringContent(deContentStr);

                        request.Content.Headers.Clear();
                        foreach (var header in originContent.Headers)
                        {
                            request.Content.Headers.Add(header.Key, header.Value);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                LogUitl.Error(ex, "Api.RequestAuthenticationHandler");
            }

            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

            return response;
        }

        private string TokenVerification(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                return null;
            }

            string loginID = null;
            if (HttpRuntime.Cache[Constants.CacheKey_SessionTokenPrefix + token] == null) //如果过期,则尝试从DB中恢复授权状态
            {
                using (var da = BaseUtil.CreateDataAccess())
                {
                    //loginID = 根据Token获取登录用户ID逻辑
                    if (!string.IsNullOrEmpty(loginID))
                    {
                        HttpRuntime.Cache.Insert(Constants.CacheKey_SessionTokenPrefix + token, loginID, null, Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1));
                    }
                }
            }
            else
            {
                loginID = HttpRuntime.Cache[Constants.CacheKey_SessionTokenPrefix + token].ToNotNullString();
            }

            return loginID;

        }

    }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

6.HandleExceptionFilterAttribute(全局异常处理过滤器,只要某个ACTION发生异常就会报被该过滤器捕获并处理)

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
    /// <summary>
    /// 统一全局异常过滤处理
    /// </summary>
    public class HandleExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            string ctrllerName = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName;
            string actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
            string sqlCmd = null;
            if (actionExecutedContext.ActionContext.ActionArguments.ContainsKey("sqlCmd"))
            {
                sqlCmd = BaseUtil.SerializeToJson(actionExecutedContext.ActionContext.ActionArguments["sqlCmd"] as SqlCmdInfo);
            }

            //记录到日志表中
            LogUitl.Error(actionExecutedContext.Exception.Message, "Api.HandleExceptionFilterAttribute",
                            string.Format("SqlCmdInfo:{0};StackTrace:{1}", sqlCmd, actionExecutedContext.Exception.StackTrace));

            var errResult = new ApiResultInfo(false, sqlCmd, actionName + "Err", actionExecutedContext.Exception.Message);
            errResult.ExtendedData["StackTrace"] = actionExecutedContext.Exception.StackTrace;

            actionExecutedContext.Response = actionExecutedContext.ActionContext.Request.CreateResponse(HttpStatusCode.OK, errResult, "application/json");

        }
    }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

7.ApiResultInfo(API返回结果实体类)

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
    [Serializable]
    public class ApiResultInfo
    {
        public bool Stauts { get; set; }

        public object Data { get; set; }

        public string ErrCode { get; set; }

        public string ErrMsg { get; set; }

        public Dictionary<string, object> ExtendedData { get; set; }

        public ApiResultInfo()
        {
            this.ExtendedData = new Dictionary<string, object>();
        }

        public ApiResultInfo(bool status, object data = null, string errCode = null, string errMsg = null, Dictionary<string, object> extData = null)
        {
            this.Stauts = status;
            this.Data = data;
            this.ErrCode = errCode;
            this.ErrMsg = errMsg;
            this.ExtendedData = extData;
            if (this.ExtendedData == null)
            {
                this.ExtendedData = new Dictionary<string, object>();
            }
        }

        /// <summary>
        /// 构建成功结果对象
        /// </summary>
        /// <param name="data"></param>
        /// <param name="extData"></param>
        /// <returns></returns>
        public static ApiResultInfo BuildOKResult(object data = null, Dictionary<string, object> extData = null)
        {
            return new ApiResultInfo(true, data, extData: extData);
        }

        /// <summary>
        /// 构建错误结果对象
        /// </summary>
        /// <param name="errCode"></param>
        /// <param name="errMsg"></param>
        /// <param name="extData"></param>
        /// <returns></returns>
        public static ApiResultInfo BuildErrResult(string errCode = null, string errMsg = null, Dictionary<string, object> extData = null)
        {
            return new ApiResultInfo(false, errCode: errCode, errMsg: errMsg, extData: extData);
        }
    }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

8.非对称加解密算法(允许客户端请求时进行公钥加密请求内容,然后服务端API中通过RequestAuthenticationHandler自定义验证管道解密请求内容)

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
        /// <summary>
        /// 生成公钥及私钥对
        /// </summary>
        /// <param name="publickey"></param>
        /// <param name="privatekey"></param>
        public static void GeneratePublicAndPrivateKey(out string publickey, out string privatekey)
        {
            RSACryptoServiceProvider crypt = new RSACryptoServiceProvider();
            publickey = crypt.ToXmlString(false);//公钥
            privatekey = crypt.ToXmlString(true);//私钥
        }

        /// <summary>
        /// 分段使用公钥加密
        /// </summary>
        /// <param name="publicKey"></param>
        /// <param name="rawInput"></param>
        /// <returns></returns>
        public static string RSAEncrypt(string publicKey, string rawInput)
        {
            if (string.IsNullOrEmpty(rawInput))
            {
                return string.Empty;
            }

            if (string.IsNullOrWhiteSpace(publicKey))
            {
                throw new ArgumentException("Invalid Public Key");
            }

            using (var rsaProvider = new RSACryptoServiceProvider())
            {
                var inputBytes = Encoding.UTF8.GetBytes(rawInput);//有含义的字符串转化为字节流
                rsaProvider.FromXmlString(publicKey);//载入公钥
                int bufferSize = (rsaProvider.KeySize / 8) - 11;//单块最大长度
                var buffer = new byte[bufferSize];
                using (MemoryStream inputStream = new MemoryStream(inputBytes),
                     outputStream = new MemoryStream())
                {
                    while (true)
                    { //分段加密
                        int readSize = inputStream.Read(buffer, 0, bufferSize);
                        if (readSize <= 0)
                        {
                            break;
                        }

                        var temp = new byte[readSize];
                        Array.Copy(buffer, 0, temp, 0, readSize);
                        var encryptedBytes = rsaProvider.Encrypt(temp, false);
                        outputStream.Write(encryptedBytes, 0, encryptedBytes.Length);
                    }
                    return Convert.ToBase64String(outputStream.ToArray());//转化为字节流方便传输
                }
            }
        }

        /// <summary>
        /// 分段使用私钥解密
        /// </summary>
        /// <param name="privateKey"></param>
        /// <param name="encryptedInput"></param>
        /// <returns></returns>
        public static string RSADecrypt(string privateKey, string encryptedInput)
        {
            if (string.IsNullOrEmpty(encryptedInput))
            {
                return string.Empty;
            }

            if (string.IsNullOrWhiteSpace(privateKey))
            {
                throw new ArgumentException("Invalid Private Key");
            }

            using (var rsaProvider = new RSACryptoServiceProvider())
            {
                var inputBytes = Convert.FromBase64String(encryptedInput);
                rsaProvider.FromXmlString(privateKey);
                int bufferSize = rsaProvider.KeySize / 8;
                var buffer = new byte[bufferSize];
                using (MemoryStream inputStream = new MemoryStream(inputBytes),
                     outputStream = new MemoryStream())
                {
                    while (true)
                    {
                        int readSize = inputStream.Read(buffer, 0, bufferSize);
                        if (readSize <= 0)
                        {
                            break;
                        }

                        var temp = new byte[readSize];
                        Array.Copy(buffer, 0, temp, 0, readSize);
                        var rawBytes = rsaProvider.Decrypt(temp, false);
                        outputStream.Write(rawBytes, 0, rawBytes.Length);
                    }
                    return Encoding.UTF8.GetString(outputStream.ToArray());
                }
            }
        }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

9.LogUitl(基于NLOG.MONGO组件简单封装实现MONGODB日志功能)--后期有机会再单独讲MONGODB的相关知识

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
    public static class LogUitl
    {
        private static NLog.Logger _Logger = null;
        private const string cacheKey_NLogConfigFlag = "NLogConfigFlag";
        private static Logger GetLogger()
        {
            if (_Logger == null || HttpRuntime.Cache[cacheKey_NLogConfigFlag] == null)
            {
                LoggingConfiguration config = new LoggingConfiguration();

                string connSetStr = ConfigUtility.GetAppSettingValue("MongoDbConnectionSet");

                MongoTarget mongoTarget = new MongoTarget();
                mongoTarget.ConnectionString = EncryptUtility.Decrypt(connSetStr);
                mongoTarget.DatabaseName = "KYELog";
                mongoTarget.CollectionName = "KYCallCenterLog";
                mongoTarget.IncludeDefaults = false;
                AppendLogMongoFields(mongoTarget.Fields);

                LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, mongoTarget);
                config.LoggingRules.Add(rule1);
                LogManager.Configuration = config;

                _Logger = LogManager.GetCurrentClassLogger();

                HttpRuntime.Cache.Insert(cacheKey_NLogConfigFlag, "Nlog", new System.Web.Caching.CacheDependency(HttpContext.Current.Server.MapPath("~/Web.config")));
            }

            return _Logger;

        }

        private static void AppendLogMongoFields(IList<MongoField> mongoFields)
        {
            mongoFields.Clear();
            Type logPropertiesType = typeof(SysLogInfo.LogProperties);
            foreach (var pro in typeof(SysLogInfo).GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (pro.PropertyType == logPropertiesType) continue;

                string layoutStr = string.Empty; //"${event-context:item=" + pro.Name + "}";
                if (pro.Name.Equals("ThreadID") || pro.Name.Equals("Level") || pro.Name.Equals("MachineName"))
                {
                    layoutStr = "${" + pro.Name.ToLower() + "}";
                }
                else if (pro.Name.Equals("LogDT"))
                {
                    layoutStr = "${date:format=yyyy-MM-dd HH\\:mm\\:ss}";
                }
                else if (pro.Name.Equals("Msg"))
                {
                    layoutStr = "${message}";
                }

                if (!string.IsNullOrEmpty(layoutStr))
                {
                    mongoFields.Add(new MongoField(pro.Name, layoutStr, pro.PropertyType.Name));
                }
            }
        }

        private static LogEventInfo BuildLogEventInfo(LogLevel level, string msg, string source, string detailTrace = null, string other1 = null, string other2 = null, string other3 = null)
        {
            var eventInfo = new LogEventInfo();
            eventInfo.Level = level;
            eventInfo.Message = msg;
            eventInfo.Properties["DetailTrace"] = detailTrace ?? string.Empty;
            eventInfo.Properties["Source"] = source ?? string.Empty;
            eventInfo.Properties["Other1"] = other1 ?? string.Empty;
            eventInfo.Properties["Other2"] = other2 ?? string.Empty;
            eventInfo.Properties["Other3"] = other3 ?? string.Empty;

            string uid = string.Empty;
            if (HttpContext.Current.User != null)
            {
                uid = HttpContext.Current.User.Identity.Name;
            }
            eventInfo.Properties["UserID"] = uid;

            return eventInfo;
        }

        public static void Info(string msg, string source, string detailTrace = null, string other1 = null, string other2 = null, string other3 = null)
        {
            try
            {
                var eventInfo = BuildLogEventInfo(LogLevel.Info, msg, source, detailTrace, other1, other2, other3);
                var logger = GetLogger();
                logger.Log(eventInfo);
            }
            catch
            { }
        }

        public static void Warn(string msg, string source, string detailTrace = null, string other1 = null, string other2 = null, string other3 = null)
        {
            try
            {
                var eventInfo = BuildLogEventInfo(LogLevel.Warn, msg, source, detailTrace, other1, other2, other3);

                var logger = GetLogger();
                logger.Log(eventInfo);
            }
            catch
            { }
        }

        public static void Error(string msg, string source, string detailTrace = null, string other1 = null, string other2 = null, string other3 = null)
        {
            try
            {
                var eventInfo = BuildLogEventInfo(LogLevel.Error, msg, source, detailTrace, other1, other2, other3);

                var logger = GetLogger();
                logger.Log(eventInfo);
            }
            catch
            { }
        }

        public static void Error(Exception ex, string source, string other1 = null, string other2 = null, string other3 = null)
        {
            try
            {
                var eventInfo = BuildLogEventInfo(LogLevel.Error, ex.Message, source, ex.StackTrace, other1, other2, other3);

                var logger = GetLogger();
                logger.Log(eventInfo);
            }
            catch
            { }
        }

    }

    public class SysLogInfo
    {
        public DateTime LogDT { get; set; }

        public int ThreadID { get; set; }

        public string Level { get; set; }

        public string Msg { get; set; }

        public string MachineName { get; set; }

        public LogProperties Properties { get; set; }

        public class LogProperties
        {
            public string Source { get; set; }

            public string DetailTrace { get; set; }

            public string UserID { get; set; }

            public string Other1 { get; set; }

            public string Other2 { get; set; }

            public string Other3 { get; set; }
        }

    }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

10.其它一些用到的公共实用方法

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
//BaseUtil:
        public static DataAccess CreateDataAccess(string connName = "DefaultConnectionString")
        {
            return new DataAccess(connName, EncryptUtility.Decrypt);
        }

        public static string SerializeToJson(object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        public static JObject DeserializeObject(string json)
        {
            return JObject.Parse(json);
        }

        public static T DeserializeObject<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }

//=====================================

    /// <summary>
    /// 类型扩展方法集合
    /// </summary>
    public static class TypeExtension
    {
        /// <summary>
        /// 转换为不为空的字符串(即:若为空,则返回为空字符串,而不是Null)
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToNotNullString(this object obj)
        {
            if (obj == null || obj == DBNull.Value)
            {
                return string.Empty;
            }
            return obj.ToString();
        }

        /// <summary>
        /// 判断列表中是否存在项
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static bool HasItem(this IEnumerable<object> list)
        {
            if (list != null && list.Any())
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// 从字答串左边起取出指定长度的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string Left(this string str, int length)
        {
            if (string.IsNullOrEmpty(str))
            {
                return string.Empty;
            }

            return str.Substring(0, length);
        }

        /// <summary>
        /// 从字答串右边起取出指定长度的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string Right(this string str, int length)
        {
            if (string.IsNullOrEmpty(str))
            {
                return string.Empty;
            }

            return str.Substring(str.Length - length);
        }

        /// <summary>
        /// 判断DataSet指定表是否包含记录
        /// </summary>
        /// <param name="ds"></param>
        /// <param name="tableIndex"></param>
        /// <returns></returns>
        public static bool HasRows(this DataSet ds, int tableIndex = 0)
        {
            if (ds != null && ds.Tables[tableIndex].Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 通用类型转换方法,EG:"".As<String>()
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T As<T>(this object obj)
        {
            T result;
            try
            {
                Type type = typeof(T);
                if (type.IsNullableType())
                {
                    if (obj == null || obj.ToString().Length == 0)
                    {
                        result = default(T);
                    }
                    else
                    {
                        type = type.GetGenericArguments()[0];
                        result = (T)Convert.ChangeType(obj, type);
                    }
                }
                else
                {
                    if (obj == null)
                    {
                        if (type == typeof(string))
                        {
                            result = (T)Convert.ChangeType(string.Empty, type);
                        }
                        else
                        {
                            result = default(T);
                        }
                    }
                    else
                    {
                        result = (T)Convert.ChangeType(obj, type);
                    }
                }
            }
            catch
            {
                result = default(T);
            }

            return result;
        }

        /// <summary>
        /// 判断是否为可空类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool IsNullableType(this Type type)
        {
            return (type.IsGenericType &&
              type.GetGenericTypeDefinition().Equals
              (typeof(Nullable<>)));
        }

        /// <summary>
        /// 尝试将ArrayList转换为Array,如果为空则转换为null
        /// </summary>
        /// <param name="arrList"></param>
        /// <returns></returns>
        public static object[] TryToArray(this ArrayList arrList)
        {
            return arrList != null ? arrList.ToArray() : null;
        }
    }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

WebApiConfig增加上述定义的一些过滤器、处理管道,以便实现拦截处理:

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Filters.Add(new HandleExceptionFilterAttribute());//添加统一处理异常过滤器

            config.MessageHandlers.Add(new RequestAuthenticationHandler());//添加统一TOKEN身份证码

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver { IgnoreSerializableAttribute = true };
        }
    }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

客户端调用上述API相关核心代码:

1.DataService(客户端访问API通用类,通过该类公共静态方法可以进行数据库的CRUD)

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
    public class DataService : BaseService
    {

        #region 私有方法
        private static SqlCmdInfo BuildSqlCmdInfo(string sqlCmdText, bool isSPCmdType = false, int dbType = 0, params object[] sqlParams)
        {
            var sqlCmdInfo = new SqlCmdInfo()
            {
                SqlCmdText = sqlCmdText,
                DbType = dbType,
                IsSPCmdType = isSPCmdType
            };

            if (sqlParams != null && sqlParams.Length > 0)
            {
                sqlCmdInfo.Parameters = new ArrayList(sqlParams);
            }

            return sqlCmdInfo;
        }

        private static string GetRrequestApiUrl(string action)
        {
            string requestApiUrl = string.Format("http://{0}/api/Data/{1}", ApiHost, action);
            return requestApiUrl;
        }

        #endregion

        public static ApiResultInfo<string> Login(string uid, string pwd, string mac, string pcName)
        {
            var result = WebApiUtil.GetResultFromWebApi<string>(null, new[] { uid, pwd, mac, pcName }, GetRrequestApiUrl("Login"));
            if (result.Stauts)
            {
                SessionToken = result.Data;
            }

            return result;
        }

        public static void LogOut()
        {
            WebApiUtil.GetResultFromWebApi<string>(AddHeadersWithToken(), string.Format("{\"\":\"{0}\"}", SessionToken), GetRrequestApiUrl("LogOut"));
        }

        public static T GetValue<T>(string sqlCmdText, object[] sqlParams = null, bool isSPCmdType = false, int dbType = 0)
        {
            var sqlCmdInfo = BuildSqlCmdInfo(sqlCmdText, isSPCmdType, dbType, sqlParams);
            var result = WebApiUtil.GetResultFromWebApi<T>(AddHeadersWithToken(), sqlCmdInfo, GetRrequestApiUrl("GetValue"));
            if (result.Stauts)
            {
                return result.Data;
            }
            throw new Exception(result.ErrCode + ":" + result.ErrMsg);
        }

        public static DataSet GetDataSet(string sqlCmdText, object[] sqlParams = null, bool isSPCmdType = false, int dbType = 0)
        {
            var sqlCmdInfo = BuildSqlCmdInfo(sqlCmdText, isSPCmdType, dbType, sqlParams);
            var result = WebApiUtil.GetResultFromWebApi<DataSet>(AddHeadersWithToken(), sqlCmdInfo, GetRrequestApiUrl("GetDataSet"));
            if (result.Stauts)
            {
                return result.Data;
            }
            throw new Exception(result.ErrCode + ":" + result.ErrMsg);
        }

        public static DataTable GetDataTable(string sqlCmdText, object[] sqlParams = null, bool isSPCmdType = false, int dbType = 0)
        {
            var sqlCmdInfo = BuildSqlCmdInfo(sqlCmdText, isSPCmdType, dbType, sqlParams);
            var result = WebApiUtil.GetResultFromWebApi<DataTable>(AddHeadersWithToken(), sqlCmdInfo, GetRrequestApiUrl("GetDataTable"));
            if (result.Stauts)
            {
                return result.Data;
            }
            throw new Exception(result.ErrCode + ":" + result.ErrMsg);
        }

        public static int ExecuteCommand(string sqlCmdText, object[] sqlParams = null, bool isSPCmdType = false, int dbType = 0)
        {
            var sqlCmdInfo = BuildSqlCmdInfo(sqlCmdText, isSPCmdType, dbType, sqlParams);
            var result = WebApiUtil.GetResultFromWebApi<int>(AddHeadersWithToken(), sqlCmdInfo, GetRrequestApiUrl("ExecuteCommand"));
            if (result.Stauts)
            {
                return result.Data;
            }
            throw new Exception(result.ErrCode + ":" + result.ErrMsg);
        }

        public static bool BatchExecuteCommand(IEnumerable<SqlCmdInfo> sqlCmdInfos)
        {
            var result = WebApiUtil.GetResultFromWebApi<bool>(AddHeadersWithToken(), sqlCmdInfos, GetRrequestApiUrl("BatchExecuteCommand"));
            if (result.Stauts)
            {
                return result.Data;
            }
            throw new Exception(result.ErrCode + ":" + result.ErrMsg);
        }

        public static void ExecuteCommandAsync(string sqlCmdText, object[] sqlParams = null, bool isSPCmdType = false, int dbType = 0, Action<ApiResultInfo<object>> callBackAction = null)
        {
            var sqlCmdInfo = BuildSqlCmdInfo(sqlCmdText, isSPCmdType, dbType, sqlParams);

            Func<SqlCmdInfo, ApiResultInfo<object>> execCmdFunc = new Func<SqlCmdInfo, ApiResultInfo<object>>((sqlCmdObj) =>
            {
                var result = WebApiUtil.GetResultFromWebApi<object>(AddHeadersWithToken(), sqlCmdObj, GetRrequestApiUrl("ExecuteCommandAsync"));
                return result;
            });

            execCmdFunc.BeginInvoke(sqlCmdInfo, new AsyncCallback((ar) =>
            {
                ApiResultInfo<object> apiResult = null;
                try
                {
                    var func = ar.AsyncState as Func<SqlCmdInfo, ApiResultInfo<object>>;
                    apiResult = func.EndInvoke(ar);
                }
                catch (Exception ex)
                {
                    apiResult = new ApiResultInfo<object>(false, ex, "ExecuteCommandAsyncErr", ex.Message);
                }
                if (callBackAction != null)
                {
                    callBackAction(apiResult);
                }
            }), execCmdFunc);
        }

        public static void SaveLogAsync(string logType, string msg, string source, string detailTrace = null, string other1 = null, string other2 = null, string other3 = null)
        {
            string[] logInfo = new[] { logType, msg, source, detailTrace, other1, other2, other3 };

            Task.Factory.StartNew((o) =>
            {
                try
                {
                    string[] logInfoObj = o as string[];
                    var result = WebApiUtil.HttpRequestToString(AddHeadersWithToken(), logInfoObj, GetRrequestApiUrl("SaveLog"));
                }
                catch
                { }
            }, logInfo);
        }

    }

    public abstract class BaseService
    {
        public static string SessionToken = null;
        public static string ApiHost = null;

        protected static Dictionary<string, string> AddHeadersWithToken()
        {
            return new Dictionary<string, string> {
                {"AccessToken",SessionToken}
            };
        }

    }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

2.WebApiUtil(WEB API请求工具类)

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
    /// <summary>
    /// WebApi实用工具类
    /// Author:Zuowenjun
    /// Date:2017/11/3
    /// </summary>
    public static class WebApiUtil
    {
        private const string rsaPublicKey = "公钥字符串";

        static WebApiUtil()
        {
            System.Net.ServicePointManager.DefaultConnectionLimit = 512;
        }

        /// <summary>
        /// 获取API结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="requestHeaders"></param>
        /// <param name="requestMsg"></param>
        /// <param name="apiUrl"></param>
        /// <param name="requestMethod"></param>
        /// <returns></returns>
        public static ApiResultInfo<T> GetResultFromWebApi<T>(Dictionary<string, string> requestHeaders, object requestMsg, string apiUrl, string requestMethod = "POST")
        {
            string retString = HttpRequestToString(requestHeaders, requestMsg, apiUrl, requestMethod);
            return JsonConvert.DeserializeObject<ApiResultInfo<T>>(retString);
        }

        /// <summary>
        /// 发送Http请求,模拟访问指定的Url,返回响应内容转换成JSON对象
        /// </summary>
        /// <param name="requestHeaders"></param>
        /// <param name="requestMsg"></param>
        /// <param name="apiUrl"></param>
        /// <param name="requestMethod"></param>
        /// <returns></returns>
        public static JObject HttpRequestToJson(Dictionary<string, string> requestHeaders, object requestMsg, string apiUrl, string requestMethod = "POST")
        {
            string retString = HttpRequestToString(requestHeaders, requestMsg, apiUrl, requestMethod);
            return JObject.Parse(retString);
        }

        /// <summary>
        /// 发送Http请求,模拟访问指定的Url,返回响应内容文本
        /// </summary>
        /// <param name="requestHeaders">请求头</param>
        /// <param name="requestData">请求体(若为GetMethod时,则该值应为空)</param>
        /// <param name="apiUrl">要访问的Url</param>
        /// <param name="requestMethod">请求方式</param>
        /// <param name="isEncryptBody">是否对请求体内容进行公钥加密</param>
        /// <returns>响应内容(响应头、响应体)</returns>
        public static string HttpRequestToString(Dictionary<string, string> requestHeaders, object requestMsg, string apiUrl, string requestMethod = "POST", bool isEncryptBody = true)
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
            request.Method = requestMethod;
            request.KeepAlive = false;
            request.Proxy = null;
            request.ServicePoint.UseNagleAlgorithm = false;
            request.AllowWriteStreamBuffering = false;
            request.ContentType = "application/json";

            if (requestHeaders != null)
            {
                foreach (var item in requestHeaders)
                {
                    request.Headers.Add(item.Key, item.Value);
                }
            }
            request.Headers.Set("Pragma", "no-cache");

            if (requestMsg != null)
            {
                string dataStr = JsonConvert.SerializeObject(requestMsg);

                if (isEncryptBody)
                {
                    request.Headers.Add("Encryption", "1");
                    dataStr = RSAEncrypt(rsaPublicKey, dataStr);//加密请求内容
                }

                byte[] data = Encoding.UTF8.GetBytes(dataStr);
                request.ContentLength = data.Length;

                using (Stream myRequestStream = request.GetRequestStream())
                {
                    myRequestStream.Write(data, 0, data.Length);
                    myRequestStream.Close();
                }
            }

            string retString = null;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                retString = GetResponseBody(response);
            }
            request = null;

            return retString;
        }

        private static string GetResponseBody(HttpWebResponse response)
        {
            string responseBody = string.Empty;
            if (response.ContentEncoding.ToLower().Contains("gzip"))
            {
                using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        responseBody = reader.ReadToEnd();
                    }
                }
            }
            else if (response.ContentEncoding.ToLower().Contains("deflate"))
            {
                using (DeflateStream stream = new DeflateStream(
                    response.GetResponseStream(), CompressionMode.Decompress))
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        responseBody = reader.ReadToEnd();
                    }
                }
            }
            else
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        responseBody = reader.ReadToEnd();
                    }
                }
            }
            return responseBody;
        }

        public static string RSAEncrypt(string publicKey, string rawInput)
        {
            if (string.IsNullOrEmpty(rawInput))
            {
                return string.Empty;
            }

            if (string.IsNullOrWhiteSpace(publicKey))
            {
                throw new ArgumentException("Invalid Public Key");
            }

            using (var rsaProvider = new RSACryptoServiceProvider())
            {
                var inputBytes = Encoding.UTF8.GetBytes(rawInput);//有含义的字符串转化为字节流
                rsaProvider.FromXmlString(publicKey);//载入公钥
                int bufferSize = (rsaProvider.KeySize / 8) - 11;//单块最大长度
                var buffer = new byte[bufferSize];
                using (MemoryStream inputStream = new MemoryStream(inputBytes),
                     outputStream = new MemoryStream())
                {
                    while (true)
                    { //分段加密
                        int readSize = inputStream.Read(buffer, 0, bufferSize);
                        if (readSize <= 0)
                        {
                            break;
                        }

                        var temp = new byte[readSize];
                        Array.Copy(buffer, 0, temp, 0, readSize);
                        var encryptedBytes = rsaProvider.Encrypt(temp, false);
                        outputStream.Write(encryptedBytes, 0, encryptedBytes.Length);
                    }
                    return Convert.ToBase64String(outputStream.ToArray());//转化为字节流方便传输
                }
            }
        }
    }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

3.ApiResultInfo(API返回结果类)、SqlCmdInfo(SQL命令信息类) 与服务端的同名类基本相同,只是少了一些方法,因为这些方法在客户端用不到所有无需再定义了:

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
    [Serializable]
    public class SqlCmdInfo
    {
        public string SqlCmdText { get; set; }

        public ArrayList Parameters { get; set; }

        public bool IsSPCmdType { get; set; }

        public int DbType { get; set; }
    }

    [Serializable]
    public class ApiResultInfo<T>
    {
        public bool Stauts { get; set; }

        public T Data { get; set; }

        public string ErrCode { get; set; }

        public string ErrMsg { get; set; }

        public Dictionary<string, object> ExtendedData { get; set; }

        public ApiResultInfo()
        {
            this.ExtendedData = new Dictionary<string, object>();
        }

        public ApiResultInfo(bool status, T data, string errCode = null, string errMsg = null, Dictionary<string, object> extData = null)
        {
            this.Stauts = status;
            this.Data = data;
            this.ErrCode = errCode;
            this.ErrMsg = errMsg;
            this.ExtendedData = extData;
            if (this.ExtendedData == null)
            {
                this.ExtendedData = new Dictionary<string, object>();
            }
        }
    }
适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

客户端使用方法如下:

//直接使用DataService的相关公共静态方法即可,就像本地直接使用ADO.NET操作数据库一样;例如:

DataTable dt = DataService.GetDataTable("SQL语句", new object[] { 参数});

DataService.ExecuteCommand("SQL语句", new Object[] { 参数 });

以上就是基于ASP.NET WEB API实现分布式数据访问中间层,这个分布式数据访问中间层虽简单,但我包含了如下几个核心内容:

1.身份验证:未经登录授权是无法访问API,当然上述的验证非常简单,这个可以根据实际情况进行扩展,比如:OA2.0验证,摘要验证等

2.请求内容加密:一些重要的请求内容必需要加密,而且防止被破解,这里使用公钥加密,私钥解密,从客户端是无法截获加密的请求内容

3.压缩响应报文:如果返回的内容过大,则需要进行压缩,以提高响应速度

4.防SQL注入:通过自定义过滤器,对传入的SQL语句利用正则进行分析,若包含非法关键字则直接不予执行且报错,执行SQL语句时也是全面采用ADO.NET的参数化,确保整个执行安全可靠。 

5.全局异常捕获:对于每个可能发生的异常一个都不放过,全部记录到日志中

6.MONGODB日志记录:利用NLOG.MONGO组件实现日志记录,不影响正常的DB

C# 实现AOP 的几种常见方式

AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的中统一处理业务逻辑的一种技术,比较常见的场景是:日志记录,错误捕获、性能监控等

AOP的本质是通过代理对象来间接执行真实对象,在代理类中往往会添加装饰一些额外的业务代码,比如如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    class RealA
    {
        public virtual string Pro { getset; }
        public virtual void ShowHello(string name)
        {
            Console.WriteLine($"Hello!{name},Welcome!");
        }
    }
//调用:
            var a = new RealA();
            a.Pro = "测试";
            a.ShowHello("梦在旅途");

这段代码很简单,只是NEW一个对象,然后设置属性及调用方法,但如果我想在设置属性前后及调用方法前后或报错都能收集日志信息,该如何做呢?可能大家会想到,在设置属性及调用方法前后都加上记录日志的代码不就可以了,虽然这样是可以,但如果很多地方都要用到这个类的时候,那重复的代码是否太多了一些吧,所以我们应该使用代理模式或装饰模式,将原有的真实类RealA委托给代理类ProxyRealA来执行,代理类中在设置属性及调用方法时,再添加记录日志的代码就可以了,这样可以保证代码的干净整洁,也便于代码的后期维护。(注意,在C#中若需被子类重写,父类必需是虚方法或虚属性virtual)

如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    class ProxyRealA : RealA
    {
        public override string Pro
        {
            get
            {
                return base.Pro;
            }
            set
            {
                ShowLog("设置Pro属性前日志信息");
                base.Pro = value;
                ShowLog($"设置Pro属性后日志信息:{value}");
            }
        }
        public override void ShowHello(string name)
        {
            try
            {
                ShowLog("ShowHello执行前日志信息");
                base.ShowHello(name);
                ShowLog("ShowHello执行后日志信息");
            }
            catch(Exception ex)
            {
                ShowLog($"ShowHello执行出错日志信息:{ex.Message}");
            }
        }
        private void ShowLog(string log)
        {
            Console.WriteLine($"{DateTime.Now.ToString()}-{log}");
        }
    }
//调用:
            var aa = new ProxyRealA();
            aa.Pro = "测试2";
            aa.ShowHello("zuowenjun.cn");

这段代码同样很简单,就是ProxyRealA继承自RealA类,即可看成是ProxyRealA代理RealA,由ProxyRealA提供各种属性及方法调用。这样在ProxyRealA类内部属性及方法执行前后都有统一记录日志的代码,不论在哪里用这个RealA类,都可以直接用ProxyRealA类代替,因为里氏替换原则,父类可以被子类替换,而且后续若想更改日志记录代码方式,只需要在ProxyRealA中更改就行了,这样所有用到的ProxyRealA类的日志都会改变,是不是很爽。上述执行结果如下图示:

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

以上通过定义代理类的方式能够实现在方法中统一进行各种执行点的拦截代码逻辑处理,拦截点(或者称为:横切面,切面点)一般主要为:执行前,执行后,发生错误,虽然解决了之前直接调用真实类RealA时,需要重复增加各种逻辑代码的问题,但随之而来的新问题又来了,那就是当一个系统中的类非常多的时候,如果我们针对每个类都定义一个代理类,那么系统的类的个数会成倍增加,而且不同的代理类中可能某些拦截业务逻辑代码都是相同的,这种情况同样是不能允许的,那有没有什么好的办法呢?答案是肯定的,以下是我结合网上资源及个人总结的如下几种常见的实现AOP的方式,各位可以参考学习。

第一种:静态织入,即:在编译时,就将各种涉及AOP拦截的代码注入到符合一定规则的类中,编译后的代码与我们直接在RealA调用属性或方法前后增加代码是相同的,只是这个工作交由编译器来完成。

PostSharp:PostSharp的Aspect是使用Attribute实现的,我们只需事先通过继承自OnMethodBoundaryAspect,然后重写几个常见的方法即可,如:OnEntry,OnExit等,最后只需要在需要进行AOP拦截的属性或方法上加上AOP拦截特性类即可。由于PostSharp是静态织入的,所以相比其它的通过反射或EMIT反射来说效率是最高的,但PostSharp是收费版本的,而且网上的教程比较多,我就不在此重复说明了,大家可以参见:使用PostSharp在.NET平台上实现AOP

第二种:EMIT反射,即:通过Emit反射动态生成代理类,如下Castle.DynamicProxy的AOP实现方式,代码也还是比较简单的,效率相对第一种要慢一点,但对于普通的反射来说又高一些,代码实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using Castle.Core.Interceptor;
using Castle.DynamicProxy;
using NLog;
using NLog.Config;
using NLog.Win32.Targets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ProxyGenerator generator = new ProxyGenerator();
            var test = generator.CreateClassProxy<TestA>(new TestInterceptor());
            Console.WriteLine($"GetResult:{test.GetResult(Console.ReadLine())}");
            test.GetResult2("test");
            Console.ReadKey();
        }
    }
    public class TestInterceptor : StandardInterceptor
    {
        private static NLog.Logger logger;
        protected override void PreProceed(IInvocation invocation)
        {
            Console.WriteLine(invocation.Method.Name + "执行前,入参:" string.Join(",", invocation.Arguments));
        }
        protected override void PerformProceed(IInvocation invocation)
        {
            Console.WriteLine(invocation.Method.Name + "执行中");
            try
            {
                base.PerformProceed(invocation);
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
        protected override void PostProceed(IInvocation invocation)
        {
            Console.WriteLine(invocation.Method.Name + "执行后,返回值:" + invocation.ReturnValue);
        }
        private void HandleException(Exception ex)
        {
            if (logger == null)
            {
                LoggingConfiguration config = new LoggingConfiguration();
                ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
                consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
                config.AddTarget("console", consoleTarget);
                LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget);
                config.LoggingRules.Add(rule1);
                LogManager.Configuration = config;
                logger = LogManager.GetCurrentClassLogger(); //new NLog.LogFactory().GetCurrentClassLogger();
            }
            logger.ErrorException("error",ex);
        }
    }
    public class TestA
    {
        public virtual string GetResult(string msg)
        {
            string str = $"{DateTime.Now.ToString("yyyy-mm-dd HH:mm:ss")}---{msg}";
            return str;
        }
        public virtual string GetResult2(string msg)
        {
            throw new Exception("throw Exception!");
        }
    }
}

简要说明一下代码原理,先创建ProxyGenerator类实例,从名字就看得出来,是代理类生成器,然后实例化一个基于继承自StandardInterceptor的TestInterceptor,这个TestInterceptor是一个自定义的拦截器,最后通过generator.CreateClassProxy<TestA>(new TestInterceptor())动态创建了一个继承自TestA的动态代理类,这个代理类只有在运行时才会生成的,后面就可以如代码所示,直接用动态代理类对象实例Test操作TestA的所有属性与方法,当然这里需要注意,若需要被动态代理类所代理并拦截,则父类的属性或方法必需是virtual,这点与我上面说的直接写一个代理类相同。

上述代码运行效果如下:

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

第三种:普通反射+利用Remoting的远程访问对象时的直实代理类来实现,代码如下,这个可能相比以上两种稍微复杂一点:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var A = new AopClass();
            A.Hello();
            var aop = new AopClassSub("梦在旅途");
            aop.Pro = "test";
            aop.Output("hlf");
            aop.ShowMsg();
            Console.ReadKey();
        }
    }
    [AopAttribute]
    public class AopClass : ContextBoundObject
    {
        public string Hello()
        {
            return "welcome";
        }
    }
    public class AopClassSub : AopClass
    {
        public string Pro = null;
        private string Msg = null;
        public AopClassSub(string msg)
        {
            Msg = msg;
        }
        public void Output(string name)
        {
            Console.WriteLine(name + ",你好!-->P:" + Pro);
        }
        public void ShowMsg()
        {
            Console.WriteLine($"构造函数传的Msg参数内容是:{Msg}");
        }
    }
    public class AopAttribute : ProxyAttribute
    {
        public override MarshalByRefObject CreateInstance(Type serverType)
        {
            AopProxy realProxy = new AopProxy(serverType);
            return realProxy.GetTransparentProxy() as MarshalByRefObject;
        }
    }
    public class AopProxy : RealProxy
    {
        public AopProxy(Type serverType)
            base(serverType) { }
        public override IMessage Invoke(IMessage msg)
        {
            if (msg is IConstructionCallMessage)
            {
                IConstructionCallMessage constructCallMsg = msg as IConstructionCallMessage;
                IConstructionReturnMessage constructionReturnMessage = this.InitializeServerObject((IConstructionCallMessage)msg);
                RealProxy.SetStubData(this, constructionReturnMessage.ReturnValue);
                Console.WriteLine("Call constructor");
                return constructionReturnMessage;
            }
            else
            {
                IMethodCallMessage callMsg = msg as IMethodCallMessage;
                IMessage message;
                try
                {
                    Console.WriteLine(callMsg.MethodName + "执行前。。。");
                    object[] args = callMsg.Args;
                    object o = callMsg.MethodBase.Invoke(GetUnwrappedServer(), args);
                    Console.WriteLine(callMsg.MethodName + "执行后。。。");
                    message = new ReturnMessage(o, args, args.Length, callMsg.LogicalCallContext, callMsg);
                }
                catch (Exception e)
                {
                    message = new ReturnMessage(e, callMsg);
                }
                Console.WriteLine(message.Properties["__Return"]);
                return message;
            }
        }
    }
}

以上代码实现步骤说明:

1.这里定义的一个真实类AopClass必需继承自ContextBoundObject类,而ContextBoundObject类又直接继承自MarshalByRefObject类,表明该类是上下文绑定对象,允许在支持远程处理的应用程序中跨应用程序域边界访问对象,说白了就是可以获取这个真实类的所有信息,以便可以被生成动态代理。

2.定义继承自ProxyAttribute的代理特性标识类AopAttribute,以表明哪些类可以被代理,同时注意重写CreateInstance方法,在CreateInstance方法里实现通过委托与生成透明代理类的过程,realProxy.GetTransparentProxy() 非常重要,目的就是根据定义的AopProxy代理类获取生成透明代理类对象实例。

3.实现通用的AopProxy代理类,代理类必需继承自RealProxy类,在这个代理类里面重写Invoke方法,该方法是统一执行被代理的真实类的所有方法、属性、字段的出入口,我们只需要在该方法中根据传入的IMessage进行判断并实现相应的拦截代码即可。

4.最后在需要进行Aop拦截的类上标注AopAttribute即可(注意:被标识的类必需是如第1条说明的继承自ContextBoundObject类),在实际调用的过程中是感知不到任何的变化。且AopAttribute可以被子类继承,也就意味着所有子类都可以被代理并拦截。

如上代码运行效果如下:

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

这里顺便分享微软官方如果利用RealProxy类实现AOP的,详见地址:https://msdn.microsoft.com/zh-cn/library/dn574804.aspx

第四种:反射+ 通过定义统一的出入口,并运用一些特性实现AOP的效果,比如:常见的MVC、WEB API中的过滤器特性 ,我这里根据MVC的思路,实现了类似的MVC过滤器的AOP效果,只是中间用到了反射,可能性能不佳,但效果还是成功实现了各种拦截,正如MVC一样,既支持过滤器特性,也支持Controller中的Action执行前,执行后,错误等方法实现拦截

实现思路如下:

A.过滤器及Controller特定方法拦截实现原理:

1.获取程序集中所有继承自Controller的类型;

2.根据Controller的名称找到第1步中的对应的Controller的类型:FindControllerType

3.根据找到的Controller类型及Action的名称找到对应的方法:FindAction

4.创建Controller类型的实例;

5.根据Action方法找到定义在方法上的所有过滤器特性(包含:执行前、执行后、错误)

6.执行Controller中的OnActionExecuting方法,随后执行执行前的过滤器特性列表,如:ActionExecutingFilter

7.执行Action方法,获得结果;

8.执行Controller中的OnActionExecuted方法,随后执行执行后的过滤器特性列表,如:ActionExecutedFilter

9.通过try catch在catch中执行Controller中的OnActionError方法,随后执行错误过滤器特性列表,如:ActionErrorFilter

10.最后返回结果;

B.实现执行路由配置效果原理:

1.增加可设置路由模板列表方法:AddExecRouteTemplate,在方法中验证controller、action,并获取模板中的占位符数组,最后保存到类全局对象中routeTemplates;

2.增加根据执行路由执行对应的Controller中的Action方法的效果: Run,在该方法中主要遍历所有路由模板,然后与实行执行的请求路由信息通过正则匹配,若匹配OK,并能正确找到Controller及Action,则说明正确,并最终统一调用:Process方法,执行A中的所有步骤最终返回结果。

需要说明该模拟MVC方案并没有实现Action方法参数的的绑定功能,因为ModelBinding本身就是比较复杂的机制,所以这里只是为了搞清楚AOP的实现原理,故不作这方面的研究,大家如果有空可以实现,最终实现MVC不仅是ASP.NET MVC,还可以是 Console MVC,甚至是Winform MVC等。

以下是实现的全部代码,代码中我已进行了一些基本的优化,可以直接使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
public abstract class Controller
{
    public virtual void OnActionExecuting(MethodInfo action)
    {
    }
    public virtual void OnActionExecuted(MethodInfo action)
    {
    }
    public virtual void OnActionError(MethodInfo action, Exception ex)
    {
    }
}
public abstract class FilterAttribute : Attribute
{
    public abstract string FilterType { get; }
    public abstract void Execute(Controller ctrller, object extData);
}
public class ActionExecutingFilter : FilterAttribute
{
    public override string FilterType => "BEFORE";
    public override void Execute(Controller ctrller, object extData)
    {
        Console.WriteLine($"我是在{ctrller.GetType().Name}.ActionExecutingFilter中拦截发出的消息!-{DateTime.Now.ToString()}");
    }
}
public class ActionExecutedFilter : FilterAttribute
{
    public override string FilterType => "AFTER";
    public override void Execute(Controller ctrller, object extData)
    {
        Console.WriteLine($"我是在{ctrller.GetType().Name}.ActionExecutedFilter中拦截发出的消息!-{DateTime.Now.ToString()}");
    }
}
public class ActionErrorFilter : FilterAttribute
{
    public override string FilterType => "EXCEPTION";
    public override void Execute(Controller ctrller, object extData)
    {
        Console.WriteLine($"我是在{ctrller.GetType().Name}.ActionErrorFilter中拦截发出的消息!-{DateTime.Now.ToString()}-Error Msg:{(extData as Exception).Message}");
    }
}
public class AppContext
{
    private static readonly Type ControllerType = typeof(Controller);
    private static readonly Dictionary<string, Type> matchedControllerTypes = new Dictionary<string, Type>();
    private static readonly Dictionary<string, MethodInfo> matchedControllerActions = new Dictionary<string, MethodInfo>();
    private Dictionary<string,string[]> routeTemplates = new Dictionary<stringstring[]>();
    public void AddExecRouteTemplate(string execRouteTemplate)
    {
        if (!Regex.IsMatch(execRouteTemplate, "{controller}", RegexOptions.IgnoreCase))
        {
            throw new ArgumentException("执行路由模板不正确,缺少{controller}");
        }
        if (!Regex.IsMatch(execRouteTemplate, "{action}", RegexOptions.IgnoreCase))
        {
            throw new ArgumentException("执行路由模板不正确,缺少{action}");
        }
        string[] keys = Regex.Matches(execRouteTemplate, @"(?<={)\w+(?=})", RegexOptions.IgnoreCase).Cast<Match>().Select(c => c.Value.ToLower()).ToArray();
        routeTemplates.Add(execRouteTemplate,keys);
    }
    public object Run(string execRoute)
    {
        //{controller}/{action}/{id}
        string ctrller = null;
        string actionName = null;
        ArrayList args = null;
        Type controllerType = null;
        bool findResult = false;
        foreach (var in routeTemplates)
        {
            string[] keys = r.Value;
            string execRoutePattern = Regex.Replace(r.Key, @"{(?<key>\w+)}", (m) => string.Format(@"(?<{0}>.[^/\\]+)", m.Groups["key"].Value.ToLower()), RegexOptions.IgnoreCase);
            args = new ArrayList();
            if (Regex.IsMatch(execRoute, execRoutePattern))
            {
                var match = Regex.Match(execRoute, execRoutePattern);
                for (int i = 0; i < keys.Length; i++)
                {
                    if ("controller".Equals(keys[i], StringComparison.OrdinalIgnoreCase))
                    {
                        ctrller = match.Groups["controller"].Value;
                    }
                    else if ("action".Equals(keys[i], StringComparison.OrdinalIgnoreCase))
                    {
                        actionName = match.Groups["action"].Value;
                    }
                    else
                    {
                        args.Add(match.Groups[keys[i]].Value);
                    }
                }
                if ((controllerType = FindControllerType(ctrller)) != null && FindAction(controllerType, actionName, args.ToArray()) != null)
                {
                    findResult = true;
                    break;
                }
            }
        }
        if (findResult)
        {
            return Process(ctrller, actionName, args.ToArray());
        }
        else
        {
            throw new Exception($"在已配置的路由模板列表中未找到与该执行路由相匹配的路由信息:{execRoute}");
        }
    }
    public object Process(string ctrller, string actionName, params object[] args)
    {
        Type matchedControllerType = FindControllerType(ctrller);
        if (matchedControllerType == null)
        {
            throw new ArgumentException($"未找到类型为{ctrller}的Controller类型");
        }
        object execResult = null;
        if (matchedControllerType != null)
        {
            var matchedController = (Controller)Activator.CreateInstance(matchedControllerType);
            MethodInfo action = FindAction(matchedControllerType, actionName, args);
            if (action == null)
            {
                throw new ArgumentException($"在{matchedControllerType.FullName}中未找到与方法名:{actionName}及参数个数:{args.Count()}相匹配的方法");
            }
            var filters = action.GetCustomAttributes<FilterAttribute>(true);
            List<FilterAttribute> execBeforeFilters = new List<FilterAttribute>();
            List<FilterAttribute> execAfterFilters = new List<FilterAttribute>();
            List<FilterAttribute> exceptionFilters = new List<FilterAttribute>();
            if (filters != null && filters.Count() > 0)
            {
                execBeforeFilters = filters.Where(f => f.FilterType == "BEFORE").ToList();
                execAfterFilters = filters.Where(f => f.FilterType == "AFTER").ToList();
                exceptionFilters = filters.Where(f => f.FilterType == "EXCEPTION").ToList();
            }
            try
            {
                matchedController.OnActionExecuting(action);
                if (execBeforeFilters != null && execBeforeFilters.Count > 0)
                {
                    execBeforeFilters.ForEach(f => f.Execute(matchedController, null));
                }
                var mParams = action.GetParameters();
                object[] newArgs = new object[args.Length];
                for (int i = 0; i < mParams.Length; i++)
                {
                    newArgs[i] = Convert.ChangeType(args[i], mParams[i].ParameterType);
                }
                execResult = action.Invoke(matchedController, newArgs);
                matchedController.OnActionExecuted(action);
                if (execBeforeFilters != null && execBeforeFilters.Count > 0)
                {
                    execAfterFilters.ForEach(f => f.Execute(matchedController, null));
                }
            }
            catch (Exception ex)
            {
                matchedController.OnActionError(action, ex);
                if (exceptionFilters != null && exceptionFilters.Count > 0)
                {
                    exceptionFilters.ForEach(f => f.Execute(matchedController, ex));
                }
            }
        }
        return execResult;
    }
    private Type FindControllerType(string ctrller)
    {
        Type matchedControllerType = null;
        if (!matchedControllerTypes.ContainsKey(ctrller))
        {
            var assy = Assembly.GetAssembly(typeof(Controller));
            foreach (var in assy.GetModules(false))
            {
                foreach (var in m.GetTypes())
                {
                    if (ControllerType.IsAssignableFrom(t) && !t.IsAbstract)
                    {
                        if (t.Name.Equals(ctrller, StringComparison.OrdinalIgnoreCase) || t.Name.Equals($"{ctrller}Controller", StringComparison.OrdinalIgnoreCase))
                        {
                            matchedControllerType = t;
                            matchedControllerTypes[ctrller] = matchedControllerType;
                            break;
                        }
                    }
                }
            }
        }
        else
        {
            matchedControllerType = matchedControllerTypes[ctrller];
        }
        return matchedControllerType;
    }
    private MethodInfo FindAction(Type matchedControllerType, string actionName, object[] args)
    {
        string ctrlerWithActionKey = $"{matchedControllerType.FullName}.{actionName}";
        MethodInfo action = null;
        if (!matchedControllerActions.ContainsKey(ctrlerWithActionKey))
        {
            if (args == null) args = new object[0];
            foreach (var in matchedControllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public))
            {
                if (m.Name.Equals(actionName, StringComparison.OrdinalIgnoreCase) && m.GetParameters().Length == args.Length)
                {
                    action = m;
                    matchedControllerActions[ctrlerWithActionKey] = action;
                    break;
                }
            }
        }
        else
        {
            action = matchedControllerActions[ctrlerWithActionKey];
        }
        return action;
    }
}

使用前,先定义一个继承自Controller的类,如:TestController,并重写相应的方法,或在指定的方法上加上所需的过滤器特性,如下代码所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class TestController : Controller
{
    public override void OnActionExecuting(MethodInfo action)
    {
        Console.WriteLine($"{action.Name}执行前,OnActionExecuting---{DateTime.Now.ToString()}");
    }
    public override void OnActionExecuted(MethodInfo action)
    {
        Console.WriteLine($"{action.Name}执行后,OnActionExecuted--{DateTime.Now.ToString()}");
    }
    public override void OnActionError(MethodInfo action, Exception ex)
    {
        Console.WriteLine($"{action.Name}执行,OnActionError--{DateTime.Now.ToString()}:{ex.Message}");
    }
    [ActionExecutingFilter]
    [ActionExecutedFilter]
    public string HelloWorld(string name)
    {
        return ($"Hello World!->{name}");
    }
    [ActionExecutingFilter]
    [ActionExecutedFilter]
    [ActionErrorFilter]
    public string TestError(string name)
    {
        throw new Exception("这是测试抛出的错误信息!");
    }
    [ActionExecutingFilter]
    [ActionExecutedFilter]
    public int Add(int a, int b)
    {
        return a + b;
    }
}

最后前端实际调用就非常简单了,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class MVCProgram
{
    static void Main(string[] args)
    {
        try
        {
            var appContext = new AppContext();
            object rs = appContext.Process("Test""HelloWorld""梦在旅途");
            Console.WriteLine($"Process执行的结果1:{rs}");
            Console.WriteLine("=".PadRight(50, '='));
            appContext.AddExecRouteTemplate("{controller}/{action}/{name}");
            appContext.AddExecRouteTemplate("{action}/{controller}/{name}");
            object result1 = appContext.Run("HelloWorld/Test/梦在旅途-zuowenjun.cn");
            Console.WriteLine($"执行的结果1:{result1}");
            Console.WriteLine("=".PadRight(50, '='));
            object result2 = appContext.Run("Test/HelloWorld/梦在旅途-zuowenjun.cn");
            Console.WriteLine($"执行的结果2:{result2}");
            Console.WriteLine("=".PadRight(50, '='));
            appContext.AddExecRouteTemplate("{action}/{controller}/{a}/{b}");
            object result3 = appContext.Run("Add/Test/500/20");
            Console.WriteLine($"执行的结果3:{result3}");
            object result4 = appContext.Run("Test/TestError/梦在旅途-zuowenjun.cn");
            Console.WriteLine($"执行的结果4:{result4}");
        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine($"发生错误:{ex.Message}");
            Console.ResetColor();
        }
        Console.ReadKey();
    }
}

可以看到,与ASP.NET MVC有点类似,只是ASP.NET MVC是通过URL访问,而这里是通过AppContext.Run 执行路由URL 或Process方法,直接指定Controller、Action、参数来执行。

通过以上调用代码可以看出路由配置还是比较灵活的,当然参数配置除外。如果大家有更好的想法也可以在下方评论交流,谢谢!

MVC代码执行效果如下:

适用于app.config与web.config的ConfigUtil读写工具类     基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)   基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式