title: Decoding only certain HTML tags in ASP.NET MVC
body: <p>I'm working with ASP.NET MVC 5 application. I have to output the HTML which a user has entered with some formatting. I store the HTML in the database as it is, i.e. without encoding, as it's adviced <a href="https://msdn.microsoft.com/en-us/security/aa973814.aspx" rel="nofollow">here</a>, but before showing it I encode it using MS AntiXSS library. However, I have to output some tags as HTML, e.g. make text bold or italic. What's the best approach to do that, while keeping the application safe from XSS? The idea I have is to first encode the text using AntiXssEncoder and then replace the allowed tags with the usual characters using RegExp. I know that some tools exist for it, like HTML Purifier, but I haven't found anything for ASP.</p>
  
  <p>Update:
  I've decided to use something like </p>
  
  <pre><code>    private static readonly Dictionary&lt;string, string&gt; allowedTags = new Dictionary&lt;string, string&gt;()
      {
          {"&amp;lt;p&amp;gt;", "&lt;p&gt;"},
          {"&amp;lt;/p&amp;gt;", "&lt;/p&gt;"},
          {"&amp;lt;strong&amp;gt;", "&lt;strong&gt;"},
          {"&amp;lt;/strong&amp;gt;", "&lt;/strong&gt;"},
          {"&amp;lt;em&amp;gt;", "&lt;em&gt;"},
          {"&amp;lt;/em&amp;gt;", "&lt;/em&gt;"},
          {"&amp;amp;nbsp;", " "},
          {"&amp;#13;&amp;#10;", "&lt;br&gt;"}
      };
  </code></pre>
  
  <p>and then</p>
  
  <pre><code>        StringBuilder text = new StringBuilder(AntiXssEncoder.HtmlEncode(item.Text, true));
          foreach (var tag in allowedTags)
          {
              text.Replace(tag.Key, tag.Value);
          }
  </code></pre>
  
  <p>Though I strongly dislike this solution since it lacks flexibility and I would have to manually insert each tag into the dictionary. Also, it doesn't support attributes, e.g. &lt; p align="center" > would have to be a separate value. I guess I can replace the first part of the tag like</p>
  
  <pre><code>text.Replace("&amp;lt;p", "&lt;p"); 
  </code></pre>
  
  <p>However, if some tag is called, for example, padding (I don't know all HTMl tags which exist or might appear), then it would work with it too, since its beginning will be replaced, thus turning it into a valid tag (which might be not closed, though).</p>