How to HTML Code Encode Decode in Asp.Net


The HTML character encoder converts all applicable characters to their corresponding HTML entities. Certain characters have special significance in HTML and should be converted to their correct HTML entities to preserve their meanings.

For example, it is not possible to use the
< character as it is used in the HTML syntax to create and close tags. It must be converted to its corresponding &lt; HTML entity to be displayed in the content of an HTML page. HTML entity names are case sensitive.

HtmlEncode, HtmlDecode. HTML must sometimes be encoded. This is necessary for it to be displayed as text in another HTML document. With the WebUtility.HtmlEncode and WebUtility.HtmlDecode methods in the C# language, we do this without writing any custom code.

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.

Next, HtmlEncode and HtmlDecode are also built into the Server objects in ASP.NET. These methods have no advantages over the HttpUtility methods. They are equivalent. We present an example that uses them in a Page class.

The WebUtility class is a better way to encode HTML and URLs in programs. You will want to call WebUtility.HtmlDecode and WebUtility.HtmlEncode on your strings. It is also possible to use the HttpUtility class.

Performance. In my brief benchmarks, I found Server.HtmlEncode and Server.HtmlDecode to be much faster than my home-grown version that used StringBuilder. Unless you want create a better implementation, it is best to use these Framework methods.StringBuilder.

StringBuilder. A string can be appended to a million times. This works but is slow. Its contents are copied each time data is appended.

Summary. These methods provide reliable replacement of HTML characters and are available in all your .NET programs. HtmlEncode and HtmlDecode also handle character entities. These are sequences that represent non-ASCII characters.

<%@Page ... ValidateRequest="false"%>

You’ll have to be very careful validating all the postback yourself. Easier way is to escape all the contents of textbox using JavaScript just before posting. You can escape it using same HTML escaping, then unescape in server side code.

HTML CODE:

<div>
<asp:TextBoxID="TextBox1"runat="server"Height="171px"TextMode="MultiLine"Width="353px"></asp:TextBox>
<br/>
<br/>
<asp:ButtonID="Button1"runat="server"Text="Encode"Height="31px"OnClick="Button1_Click"
Width="100px"/>
&nbsp;<asp:ButtonID="Button2"runat="server"Text="Decode"Height="31px"
onclick="Button2_Click"Width="100px"/>
<br/>
<br/>
<asp:TextBoxID="TextBox2"runat="server"Height="171px"TextMode="MultiLine"Width="353px"></asp:TextBox>
</div>

CODE BEHIND:

protectedvoid Page_Load(object sender, EventArgs e)
        {
//string htmlString = "<b>Hello world!</b>";
//Response.Write(htmlString);
// This will print: Hello world!
//string htmlEncoded = Server.HtmlEncode(htmlString);
//Response.Write(htmlEncoded);
// This will print: <b>Hello world!</b>
        }
//encode
privatestring Encode(string text)
        {
            TextBox2.Text = string.Empty;
byte[] encodedText = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(encodedText);
        }
//Decode:
privatestring Decode(stringencodedText)
        {
byte[] decodedText = System.Convert.FromBase64String(encodedText);
return System.Text.Encoding.UTF8.GetString(decodedText);
        }
StringWritertw = newSystem.IO.StringWriter();
stringsInput = string.Empty;
protectedvoid Button1_Click(object sender, EventArgs e)
        {
//sInput = TextBox1.Text;
//Server.HtmlEncode(sInput, tw);
//TextBox2.Text = tw.ToString();
            TextBox2.Text = HtmlEncode(TextBox1.Text);
        }

protectedvoid Button2_Click(object sender, EventArgs e)
        {
            TextBox1.Text = HtmlDecode(TextBox2.Text);
// TextBox1.Text = tw.ToString();
        }
//encode
publicstaticstring HtmlEncode(string text)
        {
char[] chars = HttpUtility.HtmlEncode(text).ToCharArray();
StringBuilder result = newStringBuilder(text.Length + (int)(text.Length * 0.1));

foreach (char c in chars)
            {
int value = Convert.ToInt32(c);
if (value > 127)
result.AppendFormat("&#{0};", value);
else
result.Append(c);
            }
returnresult.ToString();
        }
//Decode:
publicstaticstring HtmlDecode(string text)
        {
char[] chars = HttpUtility.HtmlDecode(text).ToCharArray();
StringBuilder result = newStringBuilder(text.Length + (int)(text.Length * 0.1));

foreach (char c in chars)
            {
int value = Convert.ToInt32(c);
if (value > 127)
result.AppendFormat("&#{0};", value);
else
result.Append(c);
            }
returnresult.ToString();
        }
//encode
publicstaticString Utf8ToString(Byte[] byteArray)
        {
UTF8Encoding coder = newUTF8Encoding(false);
returncoder.GetString(byteArray);
        }
//encode
publicstaticByte[] StringToUtf8(StringxmlString)
        {
UTF8Encoding coder = newUTF8Encoding(false);
returncoder.GetBytes(xmlString);
        }
//encode
publicstaticstring Base64EncodingMethod(stringsData)
        {
byte[] encodingDataASBytes = System.Text.Encoding.Unicode.GetBytes(sData);
stringsReturnValues = System.Convert.ToBase64String(encodingDataASBytes);
returnsReturnValues;
        }
//Decode:
//public static string Base64DecodingMethod(string sData)
//{
//    byte[] encData = System.Convert.ToBase64String(sData);
//    string result = System.Text.ASCIIEncoding.ASCII.GetString(encData);
//    return result;
//}
// Encode:
publicstaticstring EncodeTo64UTF8(stringm_enc)
        {
byte[] toEncodeAsBytes = System.Text.Encoding.UTF8.GetBytes(m_enc);
stringreturnValue = System.Convert.ToBase64String(toEncodeAsBytes);
returnreturnValue;
        }
// Decode:
publicstaticstring DecodeFrom64(stringm_enc)
        {
byte[] encodedDataAsBytes = System.Convert.FromBase64String(m_enc);
stringreturnValue = System.Text.Encoding.UTF8.GetString(encodedDataAsBytes);
returnreturnValue;
        }

Name Spaces required for Encode Decode

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
using System.IO;
using System.Net;
usingSystem.Text;

Related Posts

Previous
Next Post »

1 comments:

comments

Thanks for comments.....