目录结构如下 XXSHelper.cs工具类
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace test.Defender { public class XSSHelper { //过滤后返回的结果 public static string XssFilter(string html) { string str = HtmlFilter(html); return str; } //过滤html public static string HtmlFilter(string Htmlstring) { //这里用正则表达式匹配到<[^>]*>全部过滤掉,当然也可以根据自身需求填写 string result = Regex.Replace(Htmlstring, @"<[^>]*>", String.Empty); return result; } } }XXSFilterAttribute.cs过滤器
using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace test.Defender { public class XSSFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { var ps = context.ActionDescriptor.Parameters; foreach (var p in ps) { if (context.ActionArguments[p.Name] != null) { 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]); } } } } private object PostModelFieldFilter(Type type, object obj) { if (obj != null) { foreach (var item in type.GetProperties()) { if (item.GetValue(obj) != null) { 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; } } }LoginController.cs控制器
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using test.Defender; using test.Jwt; using test.Models; namespace test.Controllers { [XSSFilter] //在控制器加上XXSFilter即可过滤 [ApiController] [Route("api/[controller]")] public class LoginController : Controller { private string _names = "admin"; private string _role = "admin"; //角色,对应实体类的角色,在控制器中确定角色是否允许访问 // POST: api/Login [HttpPost] public IActionResult Index([FromBody] LoginModel model) { if (_names.Contains(model.Username) && model.Password == "admin") { return Ok(new { access_token = JwtHelper.create_Token(new User(1, model.Username, _role)) }); } return Unauthorized(); } } }