MVC 记录操作日志与过滤特殊字符

最近进行的MVC系统需要用到记录操作日志和过滤特殊字符的功能,如果每个action中都调用记录日志的方法就太麻烦了,所以根据需要结合mvc的过滤机制

写了个特殊字符验证与记录操作日志的公用类:

  1  public class CustomFilterAttribute : ActionFilterAttribute
  2     {
  3         public CustomFilterAttribute()
  4         {
  5             IsLog = false;
  6             FilterSpecialChar = true;
  7         }
  8 
  9         /// <summary>
 10         /// 是否记录日志
 11         /// </summary>
 12         public bool IsLog { get; set; }
 13 
 14         /// <summary>
 15         /// 是否过滤特殊字符
 16         /// </summary>
 17         public bool FilterSpecialChar { get; set; }
 18 
 19         /// <summary>
 20         /// 登录用户
 21         /// </summary>
 22         public string UserName { get; set; }
 23 
 24         /// <summary>
 25         /// 操作简介
 26         /// </summary>
 27         public string Message { get; set; }
 28 
 29         /// <summary>
 30         /// action执行前特殊字符过滤
 31         /// </summary>
 32         /// <param name="filterContext"></param>
 33         public override void OnActionExecuting(ActionExecutingContext filterContext)
 34         {
 35             base.OnActionExecuting(filterContext);
 36 
 37             if (filterContext.ActionParameters.Count > 0)
 38             {
 39                 if (filterContext.HttpContext.Request.IsAjaxRequest())
 40                 {
 41                     if (IsContainSpecialChar(filterContext.ActionParameters))
 42                     {
 43                         var json = new JsonResult();
 44                         json.Data = new { status = false, msg = "您输入的数据中包含特殊字符。" };
 45                         json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
 46                         filterContext.Result = json;
 47                     }
 48                 }
 49                 else if (IsContainSpecialChar(filterContext.ActionParameters))
 50                 {
 51                     var ReturnUrl = "/Login/Index";
 52                     filterContext.Result = new RedirectResult(ReturnUrl);
 53                 }
 54             }
 55 
 56             return;
 57         }
 58 
 59         /// <summary>
 60         /// action执行后记录日志
 61         /// </summary>
 62         /// <param name="filterContext"></param>
 63         public override void OnActionExecuted(ActionExecutedContext filterContext)
 64         {
 65             base.OnActionExecuted(filterContext);
 66             if (this.IsLog)
 67             {
 68                 var ActionName = filterContext.ActionDescriptor.ActionName;
 69                 var Url = "/" + filterContext.ActionDescriptor.ControllerDescriptor.ControllerName + "/" + ActionName;
 70 
 71                 //var loginInfo = (ViewModel.t_User_VModel)filterContext.HttpContext.Session["userMdl"];
 72                 string OperateIP = HttpContext.Current.Request.UserHostAddress;
 73 
 74                 //登录用户
 75                 //if (loginInfo != null)
 76                 //{
 77                 //    this.UserName = loginInfo.UserName;
 78                 //}
 79                 this.UserName = "测试";
 80                 Message = filterContext.Exception == null ? "成功" : "失败" + Message;
 81 
 82                 new JiaSoftOTOSystem.BLL.OperateLog_BLL().AddOprateLog(UserName, OperateIP, Url, ActionName, Message);
 83             }
 84         }
 85 
 86         //public override void OnResultExecuting(ResultExecutingContext filterContext)
 87         //{
 88         //    base.OnResultExecuting(filterContext);
 89         //    //filterContext.HttpContext.Response.Write("返回Result之前" + Message + "<br />");
 90         //}
 91 
 92         //public override void OnResultExecuted(ResultExecutedContext filterContext)
 93         //{
 94         //    base.OnResultExecuted(filterContext);
 95         //    //filterContext.HttpContext.Response.Write("返回Result之后" + Message + "<br />");
 96         //}
 97 
 98         /// <summary>
 99         /// 验证string类型参数中是否含有特殊字符  
100         /// </summary>
101         /// <param name="paramters"></param>
102         /// <returns>有:true,没有:false</returns>
103         public bool IsContainSpecialChar(IDictionary<string, object> paramters)
104         {
105             bool bResult = false;
106             System.Text.StringBuilder strParam = new System.Text.StringBuilder();
107             foreach (var item in paramters)
108             {
109                 if (item.Value != null)
110                 {
111                     Type types = item.Value.GetType();
112                     if (types.Name.EndsWith("Model"))
113                     {
114                         System.Reflection.PropertyInfo[] ps = types.GetProperties();
115                         foreach (PropertyInfo pi in ps)
116                         {
117                             object value = pi.GetValue(item.Value, null);//用pi.GetValue获得值
118                             string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
119                             //获得属性的类型,进行判断然后进行以后的操作,例如判断获得的属性是整数
120                             if (value != null && value.ToString().Length > 0)
121                             {
122                                 if (value.GetType() == typeof(string))
123                                 {
124                                     if (FilterSpecialChar && !bResult && Regex.IsMatch(value.ToString(), @"[~<>$%^+&\/?|:{}()';=]"))
125                                     {
126                                         bResult = true;
127                                         strParam.Append(name + "=" + value.ToString().Replace("'", "").Replace(""", "").Replace("&", "&amp").Replace("<", "&lt").Replace(">", "&gt") + "|");
128                                     }
129                                     else if (IsLog)
130                                     {
131                                         strParam.Append(name + "=" + value + "|");
132                                     }
133                                 }
134                                 else if (IsLog && item.Value.GetType() == typeof(Guid) && item.Value.ToString() != Guid.Empty.ToString())
135                                 {
136                                     strParam.Append(name + "=" + value + "|");
137                                 }
138                                 else if (IsLog && (item.Value.GetType() == typeof(int) || item.Value.GetType() == typeof(decimal)) && item.Value.ToString() != "0")
139                                 {
140                                     strParam.Append(name + "=" + value + "|");
141                                 }
142                                 else if (IsLog)
143                                 {
144                                     strParam.Append(name + "=" + value + "|");
145                                 }
146                             }
147                         }
148                     }
149                     else if (item.Value != null && item.Value.ToString().Length > 0)
150                     {
151                         if (item.Value.GetType() == typeof(string))
152                         {
153                             if (FilterSpecialChar && !bResult && Regex.IsMatch(item.Value.ToString(), @"[~<>$%^+&\/?|:{}()';=]"))
154                             {
155                                 bResult = true;
156                                 strParam.Append(item.Key + "=" + item.Value.ToString().Replace("'", "").Replace(""", "").Replace("&", "&amp").Replace("<", "&lt").Replace(">", "&gt") + "|");
157                             }
158                             else if (IsLog)
159                             {
160                                 strParam.Append(item.Key + "=" + item.Value + "|");
161                             }
162                         }
163                         else if (IsLog && item.Value.GetType() == typeof(Guid) && item.Value.ToString() != Guid.Empty.ToString())
164                         {
165                             strParam.Append(item.Key + "=" + item.Value + "|");
166                         }
167                         else if (IsLog && (item.Value.GetType() == typeof(int) || item.Value.GetType() == typeof(decimal)) && item.Value.ToString() != "0")
168                         {
169                             strParam.Append(item.Key + "=" + item.Value + "|");
170                         }
171                         else if (IsLog)
172                         {
173                             strParam.Append(item.Key + "=" + item.Value + "|");
174                         }
175                     }
176                 }
177             }
178 
179             this.Message = "。参数:" + strParam.ToString();
180 
181             return false;
182         }
183 
184     }

调用方式如下:

验证结果:如果包含特殊字符:如果是ajax请求则返回json,否则返回到错误页。

原文地址:https://www.cnblogs.com/xiaoerlang90/p/5842432.html