C# HttpUtility.HtmlEncode MethodsAccess the HttpUtility class and call its methods HtmlDecode and HtmlEncode.
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.
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 such as < and >. 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.
Warning: Make sure to test that these methods cause no "malicious encoding" warnings before deploying the application.
Page that uses HttpUtility methods: C#
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);
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.
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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.