SNB Solutions - Baja California Software Company
Welcome Guest Search | Active Topics | Log In | Register

Tag as favorite
Server.HtmlEncode in ASP.NET 2.0
stoian_bycovich
#1 Posted : Friday, February 26, 2010 2:51:26 PM

Rank: Administration

Medals:

Groups: Administrators
Joined: 1/2/2010
Posts: 79
Points: 10,237
Location: Cabo San Lucas

Thanks: 0 times
Was thanked: 0 time(s) in 0 post(s)
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.

Best regards,
Stoyan Bukovich
Executive manager
SNB Solutions

Cell.: +52 6241 616969
E-mail: s.bucovich@snb-bg.com
Web: www.snb-bg.com
Sponsor  
 
Eannouncements.net SNB Solutions Eanuncios.net

Eannouncements.net the place for your announcement.

SNB Solutions - Software and computing services company.

Eanuncios.net el lugar para su anuncio.

Users browsing this topic
Guest
Tag as favorite
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.