How do you avoid XSS vulnerabilities in ASP.Net (MVC)?

tghw picture tghw · Jul 8, 2010 · Viewed 17.7k times · Source

I recently noticed that I had a big hole in my application because I had done something like:

<input type="text" value="<%= value%>" />

I know that I should have used Html.Encode, but is there any way to do that for all values, without having to do it explicitly?

Answer

George Stocker picture George Stocker · Jul 8, 2010

There's a few ways:

  • Use the <%: %> syntax in ASP.NET MVC2 / .NET 4.0. (Which is just syntactic sugar for Html.Encode())
  • Follow the directions laid out by Phil Haack where it details using the Anti-XSS library as the 'default' encoding engine for ASP.NET.