How to use Html Laundry

First of all there is the HtmlLaundryModelBinder. If you don't use any custom model binder, then this model binder will do the work for you if you installed the nuget or made the steps mentioned in the project changes section.
When you instantiate the HtmlLaundryModelBinder you must give it a whitelist name as a constructor parameter. This whitelist will be the default whitelist.
HtmlLaundryModelBinder sniffs out two attributes:
  • WhitelistAttribute
  • UIHintAttribute
  • DataTypeAttribute
  • AllowHtmlAttribute
First it searches for the WhitelistAttribute on the property actually binding. If it finds then checks the WhitelistAttribute's WhitelistName property. Then searches for that whitelist in the /Content/HtmlLaundry, /Content, AppData/HtmlLaundry and AppData folders respectively. The filename must be the given WhitelistName with .whitelist extension. If it finds the whitelist the that whitelist will be used for cleaning. If not, then checks for the WhitelistAttribute's CanUseDefaultWhitelistIfMissing boolean property. If this property true, then uses the default whitelist otherwise throws an exception.

If there is no WhitelistAttribute on the property, then the HtmlLaundryModelBinder checks for the UIHintAttribute with "html" in it's UIHint property, DataTypeAttribute with DataType.Html value or AllowHtmlAttribute. If there is one, then Html Laundry will clean the value intended for that property with the default whitelist.

You can use Html Laundry for any string you like not only for properties marked with the attributes above. In this case you'll need a HtmlLaundry instance.
var myLaundry = new HtmlLaundry(@"c:\\WhitelistFilePath/WhitelistName.whitelist");
As you can see in this case you have to use the full path to a whitelist file instead of just a name. But the HtmlLaundryModelBinder has a useful static method to get an HtmlLaundry with just the name of the whitelist:
var myLaundry = HtmlLaundryModelBinder.GetLaundry("WhitelistName");
Now you have your own Laundry. You can clean html with one line of code:
string cleanedHtml = myLaundry.CleanHtml("<b>Bold text</b><script>alert('carzy script')</script>");

Last edited Sep 24, 2011 at 5:36 PM by Tocsi, version 3

Comments

No comments yet.