How to encode and decode HTML request in ASP.NET
Post Html Code
In many case in your application, you may want user to post html tags as input through your webpage. For example, you may allow the user to input comment in the html format they want. For instance, user may want to input his comment as
<h3><font color="green"> Krishna </font>Is Great</h3>
so that comment is displayed in htmlpage as
Krishna is Great
Now, the problem here is that compilers consider these tags as very dangerous since it might affect the structure of your webpage. Moreover, user may post some hazardous html code which may even break your application if not handled properly. So, Asp.net does not allow you to post this tags directly and validates all your input values for dangerous values. However you can bypass this validation by setting ValidateRequest attribute of the page to false as shown below:
<% @ Page Language="C#" ValidateRequest="false" %>
if ValidateRequest is set to true, request validation is performed by comparing all input data to a list of potentially dangerous values. If a match occurs, ASP.NET raises an HttpRequestValidationException and will display this screen as shown below:
For .Net Framework 4 Developer, additionally you have to set the following code in web.config file.
<httpRuntime requestValidationMode="2.0" />
In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before the BeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request.
As a result, request validation errors might now occur for requests that previously did not trigger errors. To revert to the behavior of the ASP.NET 2.0 request validation feature, we have o add the following setting in the Web.config file:
<httpRuntime requestValidationMode="2.0" />
Now that you are able to posy html tags, you may also want to store this comments (html code) in database. However, Sql server does not allow you to store special character like %, < etc which are part of html tags. So, in order to overcome this issue, we have to use the htmlencode and htmldecode methods which will convert these special characters into normal alphanumeric characters.
HTMLENCODE
The HTMLEncode method applies HTML encoding to a specified string. This is useful as a quick method of encoding form data and other client request data before using it in your Web application. Encoding data converts potentially unsafe characters to their HTML-encoded equivalent.
If the string to be encoded is not DBCS, HTMLEncode converts characters as follows:
The less-than character (<) is converted to <.
The greater-than character (>) is converted to >.
The ampersand character (&) is converted to &.
The double-quote character (") is converted to ".
Any ASCII code character whose code is greater-than or equal to 0x80 is converted to <number>, where <number> is the ASCII character value.
If the string to be encoded is DBCS, HTMLEncode converts characters as follows:
All extended characters are converted.
Any ASCII code character whose code is greater-than or equal to 0x80 is converted to <number>, where <number> is the ASCII character value.
Half-width Katakana characters in the Japanese code page are not converted.
Syntax
Server.HTMLEncode(string)
Input Parameter is the string to be encoded
HTMLDECODE
The HTMLDecode <https://msdn.microsoft.com/en-us/library/ms525347.aspx> method is the reverse of html encoding and applies HTML Decoding to a specified string. So, output of htmldecode method will be the original input string to the html encode method
Syntax
Server.HTMLDecode(string)
Input Parameter is the string to be decoded
In short, The HtmlEncode method is designed to receive a string that contains HTML markup characters such as > and <. The HtmlDecode method, meanwhile, is designed to reverse those changes: it changes encoded characters back to actual HTML.
In order to understand it better , let us see a very simple example.
<asp:TextBox ID="txtInput" runat="server" Width="165px" />
<asp:Button ID="cmdEncode" runat="server" Text="Encode" onclick= "cmdEncode_Click"/>
<asp:Button ID="Button1" runat="server" Text="Decode" onclick="cmdDecode_Click"/>
<br />
<h5>Encoded/Decoded Text will be shown here</h5>
<asp:TextBox ID="txtMsg" runat="server" Width="284px" TextMode="MultiLine" Height="146px" /><br />
As you see above, we have a textbox to accept input string and we have another textbox to display the encoded/Decoded output of the text string.
Both decode and encode functions are as shown below:
StringWriter tw =new System.IO.StringWriter();
string sInput = string.Empty;
protected void cmdEncode_Click(object sender, EventArgs e)
{
// Get the String
sInput = txtInput.Text;
// Encode the HTML Code
Server.HtmlEncode(sInput, tw);
txtMsg.Text = tw.ToString();
}
protected void cmdDecode_Click(object sender, EventArgs e)
{
// Decode the HTMLCode
Server.HtmlDecode(txtMsg.Text, tw);
// Display Encoded and Decoded string in MultiLine TextBox Control
txtMsg.Text = tw.ToString();
}
Output on click of button ‘encode’
Encode method encodes user input and display it onto the txtMsg textbox
Output on click of button ‘decode’
Decode method takes encoded string from the txtMsg textbox and display it onto the txtMsg textbox itself.
Summary
You should never allow the user to enter html tags as input. However if it is needed, then these methods provide reliable replacement of HTML characters and can be used judiciously to fulfill your requirement.
here
Note: Images used on this website
are either a production of Bhaktivedanta Book Trust(https://www.krishna.com), Iskcon
Foundation or were found in google search under "Free to use and share". If any
of the images presented here violates copyright issues or infringes anyone copyright
or are not under "Fair use", then please bring it to our notice. Read
Disclaimer for more.
Share this to your friends. One of your friend is
waiting for your share.
Related Articles
Database cannot be opened due to inaccessible files or insufficient memory or disk space
How to encode and decode HTML request in ASP.NET
How AJAX Works, advantages and disadvantages
Increase performance of your website using caching
Working with server controls and HMTL controls
Show Update Progress Animation-Ajax
Post Comment