.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() == "0"));
                            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() != "0"));
                            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;
        }
    }
View Code

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

猜你喜欢

转载自www.cnblogs.com/heshuaiblog/p/11413346.html