我的一些模型属性由AllowHtml属性标记.有没有办法自动将AntiXss保护(即仅过滤允许的标签)应用于这些字段?
Sha*_*dix 10
首先,afaik,没有内置的东西.但MVC允许通过自定义ModelBinder轻松完成这些操作,您可以定义您的
public class CustomAntiXssAttribute : Attribute { }
Run Code Online (Sandbox Code Playgroud)
并用它装饰你的属性(AllowHtmlAttribute如果你愿意,甚至可以继承).然后使用模型绑定器,您可以添加特定的防xss保护:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在里面,SOME_CUSTOM_FILTER_FUNCTION_HERE您可以使用@Yogiraj建议的内容,或使用Regexp,甚至应用基于HtmlAgilityPack的过滤.
PS别忘了添加ModelBinders.Binders.DefaultBinder = new CutstomModelBinder();到Application_Start(我忘了:))
没有自动的方法。您可以做的最接近的事情是获取 AntiXss Nuget 包。然后您可以在控制器中像下面一样使用它:
Microsoft.Security.Application.Sanitizer.GetSafeHtml("YourHtml");
Run Code Online (Sandbox Code Playgroud)
或者
Microsoft.Security.Application.Encoder.HtmlEncode("YourHtml");
Run Code Online (Sandbox Code Playgroud)
如果你使用你可以使用解码它
Server.HtmlDecode("HtmlEncodedString");
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
1548 次 |
| 最近记录: |