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

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?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

Watch this video from Scott Hanselman and Phil Haack. They cover XSS, CSRF, JSON Hijacking specifically with ASP.Net MVC.

Method 3

In ASP.Net 4.0 or later, always use <%: … %> instead of <%= … %> … it does the HTML encoding for you.

Scott Gu’s explanation.

Having done that, it’s fairly straightforward to grep your code for <%= regularly as a security precaution.

Also, are you using the Microsoft Anti-XSS library?

Method 4

Syntax for HTML encoding

  1. <%: model.something %> syntax in WebForms
  2. It is automatic in Razor i.e. @model.something will auto encode automatically no
    need to do anything to encode.
  3. MVC3 HTML Helper methods return the encoded string automatically. e.g. Html.Label will return the encoded string

More about cross site scripting

Method 5

Potentially Dangerous HTML Tags:

While not an exhaustive list, the following commonly used HTML tags could allow a malicious user to inject script code:


An attacker can use HTML attributes such as src, lowsrc, style, and href in conjunction with the preceding tags to inject cross-site scripting. For example, the src attribute of the tag can be a source of injection, as shown in the following examples.
<img src="javascript:alert('hello');">
<img src="java
<img src="java

An attacker can also use the tag to inject a script by changing the MIME type as shown in the following.
<style TYPE="text/javascript">

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x