Skipping > can potentially break code. You must keep in mind that inside the <> is also html. In that case skipping > will break. If you're only escaping for between tags then you probably only need escape < and &.
In HTML, XHTML, or XML, you can use a character escape to represent any Unicode character using only ASCII letters. Character escapes used in markup include numeric character references (NCRs) and named character references. A numeric character reference in hexadecimal format.
using System.Web;
var encoded = HttpUtility.HtmlEncode(unencoded);
    Also, you can use this if you don't want to use the System.Web assembly:
var encoded = System.Security.SecurityElement.Escape(unencoded)
Per this article, the difference between System.Security.SecurityElement.Escape() and System.Web.HttpUtility.HtmlEncode() is that the former also encodes apostrophe (') characters.
If you're using .NET 4 or above and you don't want to reference System.Web, you can use WebUtility.HtmlEncode from System
var encoded = WebUtility.HtmlEncode(unencoded);
This has the same effect as HttpUtility.HtmlEncode and should be preferred over System.Security.SecurityElement.Escape.
In ASP.NET 4.0 there's new syntax to do this. Instead of
<%= HttpUtility.HtmlEncode(unencoded) %>
you can simply do
<%: unencoded %>
Read more here:
New <%: %> Syntax for HTML Encoding Output in ASP.NET 4 (and ASP.NET MVC 2)
.NET 4.0 and above:
using System.Web.Security.AntiXss;
//...
var encoded = AntiXssEncoder.HtmlEncode("input", useNamedEntities: true);
    
                If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With