'.NET library that supports Markdown subset restrictions (akin to SO comments)

What is the easiest way to implement something similar to StackOverflow comments section? They refer to it as 'mini-Markdown': only italic, bold and code is allowed. So a limited list of Markdown tags. Everything else, including HTML and other MD tags should be displayed as is (HtmlEncoded) in order to avoid XSS.

I'm using CommonMark.NET but open to any other .NET solution.

I feel like this is a very common use case and I could not find a good example and I'm not sure I'm even on the right track. There seem to be a lot of interest in implementing 'safe markdown' and I think it should boil down to be able to easily implement subsets of Markdown like the one I've described.

Most Markdown libraries would just convert all standard MD tags into HTML and leave islands of HTML untouched (as per commonmark spec). My desired behavior is to allow specifying white list of MD features (say bold and italic) and HTML encode everything else so that it could be displayed to the end user as-is.



Solution 1:[1]

So, I think you should:

  1. Sanitize and encode all html.
  2. Apply markdown (markdig should be customizable enough)
  3. Sanitize html again, removing everything short of i/b

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Leotsarev