ایجاد یک ActionFilter جهت تمیز کردن اطلاعات ورودی در ASP.NET Core
نویسنده: داود میرزایی
تاریخ: ۱۳۹۹/۰۵/۰۶ ۲۰:۱۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class SanitizeInputAttribute : ActionFilterAttribute
{
var sanitizer = new Ganss.XSS.HtmlSanitizer();
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionArguments != null)
{
foreach (var parameter in filterContext.ActionArguments)
{
var properties = parameter.Value.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(x => x.CanRead && x.CanWrite && x.PropertyType == typeof(string) && x.GetGetMethod(true).IsPublic && x.GetSetMethod(true).IsPublic);
foreach (var propertyInfo in properties)
{
if (propertyInfo.GetValue(parameter.Value) != null)
propertyInfo.SetValue(parameter.Value,
sanitizer.Sanitize(propertyInfo.GetValue(parameter.Value).ToString()));
}
}
}
}
} [SanitizeInput] public IActionResult Add(GroupDto dto)
[SanitizeInput] public IActionResult Add (string address)
var address = filterContext.HttpContext.Request.QueryString["address"] as string; filterContext.ActionParameters["address"] = sanitizer.Sanitize(address);
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class SanitizeInputAttribute : ActionFilterAttribute
{
private readonly ISanitizer _sanitizer;
public SanitizeInputAttribute()
{
_sanitizer = new Sanitizer();
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionArguments != null)
{
foreach (var parameter in filterContext.ActionArguments.ToList())
{
if (parameter.Value != null)
{
var type = parameter.Value.GetType();
if (type == typeof(string))
{
var sanitized = _sanitizer.Sanitize(parameter.Value.ToString());
filterContext.ActionArguments[parameter.Key] = sanitized;
}
else
{
var properties = parameter.Value.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(x => x.CanRead && x.CanWrite && x.PropertyType == typeof(string) &&
x.GetGetMethod(true).IsPublic && x.GetSetMethod(true).IsPublic);
foreach (var propertyInfo in properties)
{
if (propertyInfo.GetValue(parameter.Value) != null)
propertyInfo.SetValue(parameter.Value,
_sanitizer.Sanitize(propertyInfo.GetValue(parameter.Value).ToString()));
}
}
}
}
}
}
} IHtmlSanitizer sanitizer = new HtmlSanitizer(); services.AddSingleton(sanitizer);