.net core mvc model填充过滤器
在程序开发中,我们可能经常遇到所有的数据库表有相同的属性和行为,比如需要记录数据的创建人员,创建时间,修改时间和修改人。如果在每个action中都加上这些信息,代码看着比较冗余,看着不那么优雅,于是考虑添加一个过滤器,在请求进入aciton之前对模型进行填充。这样我们就不必要在每个action中进行创建时间或者登录人员的信息进行复制一类的操作,使编程过程更加专注于业务。同时,我们也可以在这里进行一些关键词的过滤或者英文单引号过滤。
在这里我选择使用的是ActionFilterAttribute,通过重写OnActionExecuting方法填充model。具体实现代码如下:
- public class ModelFillFilter : ActionFilterAttribute
- {
- public override void OnActionExecuting(ActionExecutingContext context)
- {
- base.OnActionExecuting(context);
- var parameters = context.ActionArguments;
- parameters.ForEach(parameter =>
- {
- var model = parameter.Value;
- if (model == null) return;
- var list = new ArrayList();
- if (typeof(ICollection).IsAssignableFrom(model.GetType()))
- {
- list.AddRange(model as ICollection);
- }
- else
- {
- list.Add(model);
- }
- list.ToArray().ForEach(item =>
- {
- var propertys = item.GetType().GetProperties();
- propertys.ForEach(p =>
- {
- // 替换' 解决sql注入问题
- if (p.PropertyType.Name.ToLower().Contains("string") && p.GetValue(item) != null && p.GetSetMethod() != null)
- {
- p.SetValue(item, p.GetValue(item).ToString().Replace("'", "''"));
- }
- });
- });
- });
- var tokenObj = context.HttpContext.Request.Form["token"];
- if (!string.IsNullOrEmpty(tokenObj))
- {
- var token = tokenObj.ToString();
- var userInfoService = Ioc.GetService<IUserInfoService>();
- var user = userInfoService.Get<UserInfoModel>(string.Format(" LoginToken='{0}'", token));
- if (user != null)
- {
- parameters.ForEach(parameter =>
- {
- var model = parameter.Value;
- if (model == null) return;
- var list = new ArrayList();
- if (typeof(ICollection).IsAssignableFrom(model.GetType()))
- {
- list.AddRange(model as ICollection);
- }
- else
- {
- list.Add(model);
- }
- list.ToArray().ForEach(item =>
- {
- var propertys = item.GetType().GetProperties();
- //模型处于创建状态
- bool isCreate = propertys.Any(p => p.Name.ToLower() == "id" &&
- (p.GetValue(item) == null ||
- string.IsNullOrEmpty(p.GetValue(item).ToString()) ||
- p.GetValue(item).ToString() == ""));
- if (isCreate)
- {
- propertys.ForEach(p =>
- {
- //字段填充
- if (p.Name.ToLower() == "createdby" && p.GetSetMethod() != null && user != null)
- p.SetValue(item, Convert.ToInt32(user.Id));
- else if (p.Name.ToLower() == "createdat" && p.GetSetMethod() != null)
- p.SetValue(item, DateTime.Now);
- });
- }
- //模型处于编辑状态
- bool isUpdate = propertys.Any(p => p.Name.ToLower() == "id" &&
- (p.GetValue(item) != null &&
- !string.IsNullOrEmpty(p.GetValue(item).ToString()) &&
- p.GetValue(item).ToString() != ""));
- if (isUpdate)
- {
- propertys.ForEach(p =>
- {
- //字段填充
- if (p.Name.ToLower() == "updatedby" && p.GetSetMethod() != null && user != null)
- p.SetValue(item, Convert.ToInt32(user.Id));
- else if (p.Name.ToLower() == "updatedat" && p.GetSetMethod() != null)
- p.SetValue(item, DateTime.Now);
- });
- }
- //既不是创建也不是编辑状态
- if (!isCreate && !isUpdate)
- {
- propertys.ForEach(p =>
- {
- });
- }
- });
- });
- }
- }
- }
- /// <summary>
- /// 清楚敏感词汇
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- private bool IsContainKey(string key)
- {
- return false;
- }
- }
在代码实现过程中,这里是通过判断id是否有值用来判断这次请求是添加还是修改操作,以便进行不同的赋值。都可以根据自身情况进行不同的判断。
.net core mvc model填充过滤器的更多相关文章
- .net core MVC 通过 Filters 过滤器拦截请求及响应内容
前提: 需要nuget Microsoft.Extensions.Logging.Log4Net.AspNetCore 2.2.6: Swashbuckle.AspNetCore 我暂时用的是 ...
- .net core MVC Filters 过滤器介绍
一.过滤器的优级依次介绍如下(逐次递减): Authorization Filter -> Resource Filter -> Acton Filter -> Exception ...
- ASP.NET Core MVC 过滤器介绍
过滤器的作用是在 Action 方法执行前或执行后做一些加工处理.使用过滤器可以避免Action方法的重复代码,例如,您可以使用异常过滤器合并异常处理的代码. 过滤器如何工作? 过滤器在 MVC Ac ...
- asp.net core MVC 过滤器之ActionFilter过滤器(二)
本系类将会讲解asp.net core MVC中的内置全局过滤器的使用,将分为以下章节 asp.net core MVC 过滤器之ExceptionFilter过滤器(一) asp.net core ...
- .Net Core MVC 过滤器(一)
1.过滤器 过滤器运行在MVC Action Invocation Pipeline(MVC Action 请求管道),我们称它为Filter Pipleline(过滤器管道),Filter Pi ...
- 008.Adding a model to an ASP.NET Core MVC app --【在 asp.net core mvc 中添加一个model (模型)】
Adding a model to an ASP.NET Core MVC app在 asp.net core mvc 中添加一个model (模型)2017-3-30 8 分钟阅读时长 本文内容1. ...
- asp.net core MVC 全局过滤器之ExceptionFilter异常过滤器(一)
本系类将会讲解asp.net core MVC中的内置全局过滤器的使用,将分为以下章节 asp.net core MVC 过滤器之ExceptionFilter异常过滤器(一) asp.net cor ...
- 解说asp.net core MVC 过滤器的执行顺序
asp.net core MVC 过滤器会在请求管道的各个阶段触发.同一阶段又可以注册多个范围的过滤器,例如Global范围,controller范围等.以ActionFilter为例,我们来看看过滤 ...
- Asp.Net Core MVC框架内置过滤器
第一部分.MVC框架内置过滤器 下图展示了Asp.Net Core MVC框架默认实现的过滤器的执行顺序: Authorization Filters:身份验证过滤器,处在整个过滤器通道的最顶层.对应 ...
随机推荐
- 环境管理 pipenv 的 使用
安装 pip3 install pipenv 配置 配置 环境变量 WORKON_HOME , 表示 生成的虚拟环境 文件 的 存放位置 创建虚拟环境 方式一 pipenv --python 3.7 ...
- grep正则 以.o结尾的文件
ls -l | grep *.o 查不出任何东西 . 代表一定有一个任意字符 * 重复零个到无穷多个前一个字符(所以需要前面有字符) 所以应该是 ls -l | grep '.*\.o' .*表示零个 ...
- source insight 4.0.86.0安装破解问题
source insight 4.0.86.0安装过程中碰到导入lic文件一直不正确 解决办法: 需要将SourceInsight\SW_Install\SI4安装及破解文件 目录下的sourcein ...
- tuple unpacking
拆开Tuple lax_coordinates = (33.9425, -118.408056) latitude, longitude = lax_coordinates # tuple unpac ...
- 修改host,访问指定服务器
途径: 1.hosts文件修改 以Windows文件为例:进入system32/drivers/etc/hosts 或者用一些软件比如switchhost等来进行修改 2.通过抓包工具修改 因为本人是 ...
- pgsql SQL监控,查询SQL执行情况
SELECT procpid, START, now() - START AS lap, current_query FROM ( SELECT backendid, pg_stat_get_back ...
- leetcode-15双周赛-1287-有序数组中出现次数超过25%的元素
题目描述: 方法一:二分法 class Solution: def findSpecialInteger(self, arr: List[int]) -> int: span = len(arr ...
- boost unordered
Boost.Unordered provides the classes boost::unordered_set, boost::unordered_multiset, boost::unorder ...
- k-近邻算法(kNN)笔记
#mat()函数可以将数组(array)转化为矩阵(matrix)# randMat = mat(random.rand(4,4))# 求逆矩阵:randMat.I# 存储逆矩阵:invRandMat ...
- 数字滚动动画效果 vue组件化
参考了这篇文章,作者思路很清晰,简单做了下修改,蟹蟹作者,链接在此:https://www.jb51.net/css/685357.html#comments 主要思路是利用css属性writing- ...