在程序开发中,我们可能经常遇到所有的数据库表有相同的属性和行为,比如需要记录数据的创建人员,创建时间,修改时间和修改人。如果在每个action中都加上这些信息,代码看着比较冗余,看着不那么优雅,于是考虑添加一个过滤器,在请求进入aciton之前对模型进行填充。这样我们就不必要在每个action中进行创建时间或者登录人员的信息进行复制一类的操作,使编程过程更加专注于业务。同时,我们也可以在这里进行一些关键词的过滤或者英文单引号过滤。

在这里我选择使用的是ActionFilterAttribute,通过重写OnActionExecuting方法填充model。具体实现代码如下:

  1. public class ModelFillFilter : ActionFilterAttribute
  2. {
  3. public override void OnActionExecuting(ActionExecutingContext context)
  4. {
  5. base.OnActionExecuting(context);
  6.  
  7. var parameters = context.ActionArguments;
  8.  
  9. parameters.ForEach(parameter =>
  10. {
  11. var model = parameter.Value;
  12. if (model == null) return;
  13. var list = new ArrayList();
  14.  
  15. if (typeof(ICollection).IsAssignableFrom(model.GetType()))
  16. {
  17. list.AddRange(model as ICollection);
  18. }
  19. else
  20. {
  21. list.Add(model);
  22. }
  23.  
  24. list.ToArray().ForEach(item =>
  25. {
  26. var propertys = item.GetType().GetProperties();
  27. propertys.ForEach(p =>
  28. {
  29. // 替换' 解决sql注入问题
  30. if (p.PropertyType.Name.ToLower().Contains("string") && p.GetValue(item) != null && p.GetSetMethod() != null)
  31. {
  32. p.SetValue(item, p.GetValue(item).ToString().Replace("'", "''"));
  33. }
  34. });
  35. });
  36. });
  37.  
  38. var tokenObj = context.HttpContext.Request.Form["token"];
  39.  
  40. if (!string.IsNullOrEmpty(tokenObj))
  41. {
  42. var token = tokenObj.ToString();
  43. var userInfoService = Ioc.GetService<IUserInfoService>();
  44. var user = userInfoService.Get<UserInfoModel>(string.Format(" LoginToken='{0}'", token));
  45.  
  46. if (user != null)
  47. {
  48. parameters.ForEach(parameter =>
  49. {
  50. var model = parameter.Value;
  51. if (model == null) return;
  52.  
  53. var list = new ArrayList();
  54.  
  55. if (typeof(ICollection).IsAssignableFrom(model.GetType()))
  56. {
  57. list.AddRange(model as ICollection);
  58. }
  59. else
  60. {
  61. list.Add(model);
  62. }
  63.  
  64. list.ToArray().ForEach(item =>
  65. {
  66. var propertys = item.GetType().GetProperties();
  67. //模型处于创建状态
  68. bool isCreate = propertys.Any(p => p.Name.ToLower() == "id" &&
  69. (p.GetValue(item) == null ||
  70. string.IsNullOrEmpty(p.GetValue(item).ToString()) ||
  71. p.GetValue(item).ToString() == ""));
  72. if (isCreate)
  73. {
  74. propertys.ForEach(p =>
  75. {
  76. //字段填充
  77. if (p.Name.ToLower() == "createdby" && p.GetSetMethod() != null && user != null)
  78. p.SetValue(item, Convert.ToInt32(user.Id));
  79. else if (p.Name.ToLower() == "createdat" && p.GetSetMethod() != null)
  80. p.SetValue(item, DateTime.Now);
  81. });
  82. }
  83.  
  84. //模型处于编辑状态
  85. bool isUpdate = propertys.Any(p => p.Name.ToLower() == "id" &&
  86. (p.GetValue(item) != null &&
  87. !string.IsNullOrEmpty(p.GetValue(item).ToString()) &&
  88. p.GetValue(item).ToString() != ""));
  89. if (isUpdate)
  90. {
  91. propertys.ForEach(p =>
  92. {
  93. //字段填充
  94. if (p.Name.ToLower() == "updatedby" && p.GetSetMethod() != null && user != null)
  95. p.SetValue(item, Convert.ToInt32(user.Id));
  96. else if (p.Name.ToLower() == "updatedat" && p.GetSetMethod() != null)
  97. p.SetValue(item, DateTime.Now);
  98. });
  99. }
  100.  
  101. //既不是创建也不是编辑状态
  102. if (!isCreate && !isUpdate)
  103. {
  104. propertys.ForEach(p =>
  105. {
  106.  
  107. });
  108. }
  109. });
  110. });
  111. }
  112. }
  113. }
  114.  
  115. /// <summary>
  116. /// 清楚敏感词汇
  117. /// </summary>
  118. /// <param name="key"></param>
  119. /// <returns></returns>
  120. private bool IsContainKey(string key)
  121. {
  122. return false;
  123. }
  124. }

在代码实现过程中,这里是通过判断id是否有值用来判断这次请求是添加还是修改操作,以便进行不同的赋值。都可以根据自身情况进行不同的判断。

.net core mvc model填充过滤器的更多相关文章

  1. .net core MVC 通过 Filters 过滤器拦截请求及响应内容

    前提: 需要nuget   Microsoft.Extensions.Logging.Log4Net.AspNetCore   2.2.6: Swashbuckle.AspNetCore 我暂时用的是 ...

  2. .net core MVC Filters 过滤器介绍

    一.过滤器的优级依次介绍如下(逐次递减): Authorization Filter ->  Resource Filter -> Acton Filter -> Exception ...

  3. ASP.NET Core MVC 过滤器介绍

    过滤器的作用是在 Action 方法执行前或执行后做一些加工处理.使用过滤器可以避免Action方法的重复代码,例如,您可以使用异常过滤器合并异常处理的代码. 过滤器如何工作? 过滤器在 MVC Ac ...

  4. asp.net core MVC 过滤器之ActionFilter过滤器(二)

    本系类将会讲解asp.net core MVC中的内置全局过滤器的使用,将分为以下章节 asp.net core MVC 过滤器之ExceptionFilter过滤器(一) asp.net core ...

  5. .Net Core MVC 过滤器(一)

    1.过滤器   过滤器运行在MVC Action Invocation Pipeline(MVC Action 请求管道),我们称它为Filter Pipleline(过滤器管道),Filter Pi ...

  6. 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. ...

  7. asp.net core MVC 全局过滤器之ExceptionFilter异常过滤器(一)

    本系类将会讲解asp.net core MVC中的内置全局过滤器的使用,将分为以下章节 asp.net core MVC 过滤器之ExceptionFilter异常过滤器(一) asp.net cor ...

  8. 解说asp.net core MVC 过滤器的执行顺序

    asp.net core MVC 过滤器会在请求管道的各个阶段触发.同一阶段又可以注册多个范围的过滤器,例如Global范围,controller范围等.以ActionFilter为例,我们来看看过滤 ...

  9. Asp.Net Core MVC框架内置过滤器

    第一部分.MVC框架内置过滤器 下图展示了Asp.Net Core MVC框架默认实现的过滤器的执行顺序: Authorization Filters:身份验证过滤器,处在整个过滤器通道的最顶层.对应 ...

随机推荐

  1. 环境管理 pipenv 的 使用

    安装 pip3 install pipenv 配置 配置 环境变量 WORKON_HOME , 表示 生成的虚拟环境 文件 的 存放位置 创建虚拟环境 方式一 pipenv --python 3.7 ...

  2. grep正则 以.o结尾的文件

    ls -l | grep *.o 查不出任何东西 . 代表一定有一个任意字符 * 重复零个到无穷多个前一个字符(所以需要前面有字符) 所以应该是 ls -l | grep '.*\.o' .*表示零个 ...

  3. source insight 4.0.86.0安装破解问题

    source insight 4.0.86.0安装过程中碰到导入lic文件一直不正确 解决办法: 需要将SourceInsight\SW_Install\SI4安装及破解文件 目录下的sourcein ...

  4. tuple unpacking

    拆开Tuple lax_coordinates = (33.9425, -118.408056) latitude, longitude = lax_coordinates # tuple unpac ...

  5. 修改host,访问指定服务器

    途径: 1.hosts文件修改 以Windows文件为例:进入system32/drivers/etc/hosts 或者用一些软件比如switchhost等来进行修改 2.通过抓包工具修改 因为本人是 ...

  6. pgsql SQL监控,查询SQL执行情况

    SELECT procpid, START, now() - START AS lap, current_query FROM ( SELECT backendid, pg_stat_get_back ...

  7. leetcode-15双周赛-1287-有序数组中出现次数超过25%的元素

    题目描述: 方法一:二分法 class Solution: def findSpecialInteger(self, arr: List[int]) -> int: span = len(arr ...

  8. boost unordered

    Boost.Unordered provides the classes boost::unordered_set, boost::unordered_multiset, boost::unorder ...

  9. k-近邻算法(kNN)笔记

    #mat()函数可以将数组(array)转化为矩阵(matrix)# randMat = mat(random.rand(4,4))# 求逆矩阵:randMat.I# 存储逆矩阵:invRandMat ...

  10. 数字滚动动画效果 vue组件化

    参考了这篇文章,作者思路很清晰,简单做了下修改,蟹蟹作者,链接在此:https://www.jb51.net/css/685357.html#comments 主要思路是利用css属性writing- ...