Attention: We are retiring the ASP.NET Community Blogs. Learn more >

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.

3 Comments

Comments have been disabled for this content.