/// <summary> /// OnActionExecuting /// </summary> /// <param name="context"></param> public override void OnActionExecuting(ActionExecutingContext context) { base.OnActionExecuting(context); if (context.ActionArguments.Count == 0) { return; } //获取参数集合 var ps = context.ActionDescriptor.Parameters; //遍历参数集合 foreach (var p in ps) { if (context.ActionArguments.ContainsKey(p.Name)) { //当参数是string if (p.ParameterType.Equals(typeof(string))) { context.ActionArguments[p.Name] = XSSHelper.XssFilter(context.ActionArguments[p.Name].ToString()); } else if (p.ParameterType.IsClass)//当参数是一个实体 { PostModelFieldFilter(p.ParameterType, context.ActionArguments[p.Name]); } } } }
/// <summary> /// 将forumViewModel转换成Forum类 /// </summary> /// <param name="id">作者ID</param> /// <param name="forumViewmodel">源目标</param> /// <returns></returns> private Forum BuildForum(string id, forumViewModel forumViewmodel) { Forum forum = new Forum(); //如果题目写成了按js代码(例如<script>alert("di")</script>),ASP.NET Core不会对其XSS过滤 //但这里不用XSSHelper过滤也可以, //详细看https://docs.microsoft.com/zh-cn/aspnet/core/security/cross-site-scripting?view=aspnetcore-2.2 //中Razor的HTML编码 // forum.Title = XSSHelper.Sanitizer(forumViewmodel.forum_Title); forum.Title = forumViewmodel.forum_Title; //这里不用XSSHelper过滤,ASP.NET Core也会帮你过滤 //(PS:这里不太懂XSS过滤机制,为什么Title属性没有XSS过滤,而forum_Content却XSS过滤了) //forum.Content = forumViewmodel.forum_Content; forum.Content = XSSHelper.Sanitizer(forumViewmodel.forum_Content); forum.CategoryId = forumViewmodel.forum_Category; forum.Create_Time = DateTime.Now; forum.UserId = id; forum.IsElite = 0; forum.ID = Guid.NewGuid().ToString("N"); return(forum); }
/// <summary> /// 遍历实体的字符串属性 /// </summary> /// <param name="type">数据类型</param> /// <param name="obj">对象</param> /// <returns></returns> private object PostModelFieldFilter(Type type, object obj) { if (obj != null) { foreach (var item in type.GetProperties()) { if (item.GetValue(obj) != null) { //当参数是str if (item.PropertyType.Equals(typeof(string))) { string value = item.GetValue(obj).ToString(); item.SetValue(obj, XSSHelper.XssFilter(value)); } else if (item.PropertyType.IsClass)//当参数是一个实体 { item.SetValue(obj, PostModelFieldFilter(item.PropertyType, item.GetValue(obj))); } } } } return(obj); }