Home
Map
HttpUtility.HtmlEncode MethodsAccess the HttpUtility class and call its methods HtmlDecode and HtmlEncode.
C#
This page was last reviewed on Oct 11, 2023.
HttpUtility. This is a useful class. It provides methods (HtmlEncode and HtmlDecode) that manipulate HTML strings. Other methods support URL encoding.
HtmlEncode, HtmlDecode
Notes, class. HttpUtility is found in the System.Web namespace. It can be used in any project, not just an ASP.NET project. We must include the System.Web namespace.
An example. Here we use the HttpUtility class. The HtmlDecode and HtmlEncode methods are ideal for changing the representation of special characters in HTML strings.
Note HTML uses some characters like angle brackets. These characters are interpreted differently than others.
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.
Detail Make sure to test that these methods cause no "malicious encoding" warnings before deploying the application.
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 = "<html>"; string value2 = HttpUtility.HtmlDecode(value1); string value3 = HttpUtility.HtmlEncode(value2); Debug.WriteLine(value1); Debug.WriteLine(value2); Debug.WriteLine(value3); } }
&lt;html&gt; <html> &lt;html&gt;
Converting. HtmlDecode and HtmlEncode are invoked with HTML parameters. The HttpUtility.HtmlDecode method transformed the encoded brackets into actual brackets.
And The HtmlEncode method translated the decoded string back to the original encoded string.
A discussion. 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.
Also The other ways to encode data in System.Web may require actual Server intrinsic objects in the ASP.NET pipeline.
A summary. We looked at HttpUtility.HtmlDecode and HtmlEncode from System.Web. We must ensure that the System.Web assembly is loaded into the assembly references in the project.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.