Some of my model properties are marked by AllowHtml attribute. Is there any way to automatically apply AntiXss protection (i. e. filter only allowed tags) to these fields?
First, afaik, nothing is built-in for that. But MVC allows to do such things easily via custom ModelBinders, you could define your
public class CustomAntiXssAttribute : Attribute { }
and decorate your properties with it (and even inherit from AllowHtmlAttribute
if you wish). Then with a model binder you could add your specific anti-xss protection:
public class CutstomModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Attributes.OfType<CustomAntiXssAttribute>().Any())
{
var valueResult = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
var filteredValue = SOME_CUSTOM_FILTER_FUNCTION_HERE(valueResult.AttemptedValue);
propertyDescriptor.SetValue(bindingContext.Model, filteredValue);
}
else // revert to the default behavior.
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
}
Then inside that SOME_CUSTOM_FILTER_FUNCTION_HERE
you could use what @Yogiraj suggested, or use a Regexp, or even apply HtmlAgilityPack-based filtering.
P.S. Don't forget to add ModelBinders.Binders.DefaultBinder = new CutstomModelBinder();
to Application_Start (I forgot :))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With