Posted by: Cirilo Meggiolaro | 04/19/2009

Tip of the day #187 – ASP.NET MVC – Encoding text outputs

Attacks to web sites are really common and one of the most common attacks is the injection attack. Today’s tip shows how to encode texts to avoid JavaScript attacks.

Let’s assume your Controller class has the following action method:

public ActionResult Index()
    ViewData[“Message”] = “A text to display on the view.”;
    return View();

When you add the code below to your Index.aspx View you will have the text displayed properly:

<%= ViewData[“Message”] %>

Output: A text to display on the view.

But a lot of applications display information entered by a user. What if a user enters the JavaScript below to a textbox that has its text saved to a database?


Without encoding this text, an alert will be displayed every time you want to display this text. Let’s check how to avoid it.

How to…

We are going to use one of two overloads of the static method Encode available under the Html class:

  • string Encode(object value);
  • string Encode(string value);

Basically most part of the time you need to display a text on a View you should encode it. The syntax is pretty straightforward.

On the Index.aspx View you will use the Encode method to encode the output:

<%= Html.Encode(ViewData[“Message”]) %>

If a malicious JavaScript is entered somewhere, the script will be displayed on the screen instead of being executed.

Keep this in mind and apply it to your applications.

See you on the next tip!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: