title: Is it safe to encode an Html string before it's inserted in an SQL database and then send it back to the browser
body: <p>I've been reading extensively for the last 2 days about securing ASP.NET applications. However there are contradictory opinions whether html form inputs should be encoded before they are inserted in a SQL database or just before they are sent back to the browser. I think the former opinion makes more sense to me and I will encode all form inputs once they are received by the server and then inserted in the database. However I'm a bit confused about what will happen next!</p>
  
  <p>So let me follow a string from the time it's created until it is sent back to the browser.</p>
  
  <p>Step 1</p>
  
  <p>A user inputs the following string:</p>
  
  <pre><code>string userString = "It's important to know that 1 &gt; 0";
  </code></pre>
  
  <p>Step 2</p>
  
  <p>Once received by the server the string is encoded and inserted in the database.</p>
  
  <pre><code>string RenderedString = HttpUtility.HtmlEncode(userString);
  </code></pre>
  
  <p>As a result the string in the database is saved as follows:</p>
  
  <pre><code>"It&amp;#39;s important to know that 1 &amp;gt; 0."
  </code></pre>
  
  <p>Step 3</p>
  
  <p>I want to send the rendered string back to the browser as it is so it will be written on the webpage as html, and not parsed and rendered by the browser. The result will be:</p>
  
  <pre><code>string StringResult = "It's important to know that 1 &gt; 0";  
  </code></pre>
  
  <p>My question is: Should I add any extra "safety" step before sending the string back to the browser or is it enough with the 3 above steps? Any help would be well appreciated?</p>