Alternative to System.Web.HttpUtility.HtmlEncode / Decode?

Is there any "subtle" alternative to the functions of System.Web.HttpUtility.HtmlEncode / .Decode in .net 3.5 (sp1)? A separate library is in order or even โ€œwantsโ€ at least something that does not pull the โ€œcompletely new worldโ€ of dependencies that System.Web requires.

I want to convert a normal string to my xml / xhtml (& back) equivalent.

+4
source share
5 answers

For XML, you just need to encode characters that have special meaning, so you can get away with something simple:

public static string XmlEncode(string value) { return value .Replace("<", "&lt;") .Replace(">", "&gt;") .Replace("\"", "&quot;") .Replace("'", "&apos;") .Replace("&", "&amp;"); } public static string XmlDecode(string value) { return value .Replace("&lt;", "<") .Replace("&gt;", ">") .Replace("&quot;", "\"") .Replace("&apos;", "'") .Replace("&amp;", "&"); } 
+5
source

In the .NET Framework 4.0 System.Net.WebUtility.HtmlEncode is possible? Note that this class is located in System.dll, not System.Web.dll .

+22
source

For HTML, if you are using the .NET Framework 4.0 System.Net.WebUtility , you cannot use this:

 string HtmlEncode(string s) { if (s == null) { return null; } var result = new StringBuilder(s.Length); foreach (char ch in s) { if (ch <= '>') { switch (ch) { case '<': result.Append("&lt;"); break; case '>': result.Append("&gt;"); break; case '"': result.Append("&quot;"); break; case '\'': result.Append("&#39;"); break; case '&': result.Append("&amp;"); break; default: result.Append(ch); break; } } else if (ch >= 160 && ch < 256) { result.Append("&#").Append(((int)ch).ToString(CultureInfo.InvariantCulture)).Append(';'); } else { result.Append(ch); } } return result.ToString(); } 

Resonance implementation:

Running a large number of notes () on a line would be very difficult, especially on large lines.

Denial of responsibility:

This solution was based on the use of JetBrains dotPeek in the assembly of the .NET Framework 4.0.

+4
source

If possible, you can "borrow" the HttpUtility class from Mono-code and compile it directly in your assembly.

+1
source

Although coding may seem simple, I highly recommend using a library that is widely used to minimize the risk of vulnerabilities. The Microsoft Anti-Cross Scripting Library provides methods for escaping HTML / Xml / Javascript and related attributes and should cover most of your web needs.

+1
source

Source: https://habr.com/ru/post/1308978/


All Articles