Server.HtmlEncode in ASP.NET 2.0

In this post I am going to show how you can avoid inserting malicious code into your html, database ... if you are get user input from forms. For this example, in aspx file I am going to use the following controls:

<asp:TextBox ID="tbText" runat="server" TextMode="MultiLine" Width="250px" Height="150px" />

<br /><br />

<asp:Button ID="btnSend" runat="server" Text="Paste into code" />

<br /><br /><br />

<asp:Label ID="lblText" runat="server" />

very simple.

In code-behind will put the following:

Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSend.Click

Dim txt As String = tbText.Text

Dim writer As New System.IO.StringWriter

Server.HtmlEncode(txt, writer)

lblText.Text = writer.ToString

End Sub

Herein I am using the "Server.HtmlEncode" object to encode the users input so for example it contains something like this <script>Alert("Hi there!");</script> it won't popup, in other words you are protected from cross-script attack. I forgot to tell you about one more essential thing.

In your aspx file in @Page declaration you have to set like this

<%@ Page Language="VB" ValidateRequest="false" ...........

That way the runtime protection mechanisum will be turned off and you will be able to use this functionality and to avoid this message:

A potentially dangerous Request.Form value was detected from the client (tbText="<script>").

And the last thing to remember is to validate all information that you get from user.

Cheers

Thank you for your question. Here is the answer:

The difference in using object is HTML-encodes a string and sends the resulting output to a TextWriter output stream. StringWriter is an implementation of TextWriter.

Published Thursday, February 21, 2008 3:37 AM by stoian bucovich

Comments

# re: Server.HtmlEncode in ASP.NET 2.0

Thursday, February 21, 2008 4:38 AM by Guy Harwood

why bother using a stringwriter?

# re: Server.HtmlEncode in ASP.NET 2.0

Monday, May 11, 2009 3:29 AM by Velan

Hi,

There are times where one cannot do this for all text boxes in every pages of an application (esp in a big application).

So What is the solution for this kind of situation.

-danny.myself@gmail.com

# re: Server.HtmlEncode in ASP.NET 2.0

Tuesday, October 27, 2009 7:16 AM by Jimit Shah

normal HTML tags like "<b></b>" will be encoded or not ?

# re: Server.HtmlEncode in ASP.NET 2.0

Thursday, May 13, 2010 11:44 PM by re: Server.HtmlEncode in ASP.NET 2.0

re: Server.HtmlEncode in ASP.NET 2.0

Leave a Comment

(required) 
(required) 
(optional)
(required)