在程序开发中,我们可能经常遇到所有的数据库表有相同的属性和行为,比如需要记录数据的创建人员,创建时间,修改时间和修改人。如果在每个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填充过滤器的更多相关文章

  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. centos7系统之telnet命令rpm包安装

    centos7系统之telnet命令rpm包安装 1. 下载安装包 rpm包下载位置:http://vault.centos.org/6.3/os/x86_64/Packages/ [root@ywb ...

  2. 五 shell 变量与字符串操作

    特点:1 shell变量没有数据类型的区分 2 Shell 把任何存储在变量中的值,皆视为以字符组成的“字符串”.    3  设定的变量值只在当前shell环境中有作用    4   不能以数字开头 ...

  3. android采集设备

    http://www.hingway.com/xindalu/xindalu-data.htm 安卓新大陆设备 wce优博讯设备

  4. 【LeetCode】回溯法 backtracking(共39题)

    [10]Regular Expression Matching [17]Letter Combinations of a Phone Number [22]Generate Parentheses ( ...

  5. bzoj4182 Shopping 点分治+单调队列优化多重背包

    题目传送门 https://lydsy.com/JudgeOnline/problem.php?id=4182 题解 有一个很直观的想法是设 \(dp[x][i]\) 表示在以 \(x\) 为根的子树 ...

  6. 接口上传base64编码图片

    package com.*.util; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io. ...

  7. 【leetcode】1022. Smallest Integer Divisible by K

    题目如下: Given a positive integer K, you need find the smallest positive integer N such that N is divis ...

  8. 【leetcode】564. Find the Closest Palindrome

    题目如下: 解题思路:既然是要求回文字符串,那么最终的输出结果就是对称的.要变成对称字符串,只要把处于对称位置上对应的两个字符中较大的那个变成较小的那个即可,假设n=1234,1和4对称所以把4变成1 ...

  9. Voting与OCR

    VotingVoting Disk里面记录着节点成员的信息.如RAC数据库中有哪些节点成员,节点增加或者删除时也同样会将信息记录进来.Voting Disk必须存放在共享存储上.crsctl quer ...

  10. selenium环境搭建,浏览器驱动安装

    一安装Python: 1.下载Phtyon地址:https://www.python.org/getit/ 2.安装python会默认安装两个基础包setuptools,pip   也可以手动安装: ...