HomeSearch

C# HttpUtility.HtmlEncode Methods

This C# article examines the HttpUtility class and its methods HtmlDecode and HtmlEncode.
HttpUtility is a useful class. It provides methods that manipulate HTML strings. These methods encode and decode HTML. This class is found in the System.Web namespace. It can be used in any project, not just an ASP.NET project.
Example. The HtmlDecode and HtmlEncode methods are ideal for changing the representation of special characters in HTML strings. HTML uses some characters such as < and >. These characters are interpreted differently than others.

Note: The angle brackets indicate the structure of the HTML document. They are critical for structure.

Here: In this example, the string literal value1 is assigned to an HTML string containing escaped HTML characters.

And: If you have unencoded user input, you must escape it before rendering it to another web page or HTTP response.

Page that uses HttpUtility methods: C# using System; using System.Diagnostics; using System.Web; using System.Web.UI; public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { // // Shows how the HtmlDecode and HtmlEncode methods work. // string value1 = "&lt;html&gt;"; string value2 = HttpUtility.HtmlDecode(value1); string value3 = HttpUtility.HtmlEncode(value2); Debug.WriteLine(value1); Debug.WriteLine(value2); Debug.WriteLine(value3); } } Debug output of the page &lt;html&gt; <html> &lt;html&gt;
Converting. HtmlDecode and HtmlEncode are invoked with HTML parameters. The original string reference value1 is unchanged by the program, but the HttpUtility.HtmlDecode method transformed the encoded brackets into actual brackets.

Finally: The HtmlEncode method translated the decoded string back to the original encoded string.

Discussion. These methods are versatile. It is easy to use the HttpUtility methods in projects that are console projects or even Windows Forms programs. These are not request-based or written for the HTTP protocol.
The other ways to encode data in System.Web may require actual Server intrinsic objects in the ASP.NET pipeline. Using the HttpUtility.HtmlDecode, HtmlEncode, UrlDecode and UrlEncode methods is practical.

Note: You can find another description of HTML encoding in ASP.NET using the Server object.

HtmlEncode, HtmlDecode
Summary. We looked at the HttpUtility.HtmlDecode and HtmlEncode methods from System.Web. These can be used in any .NET project. You must ensure that the correct System.Web assembly is loaded into the assembly references in your project.

So: These methods and the related ones on HttpUtility are ideal for processing HTML strings for user input and display.

© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls