HttpUtility.HtmlEncode 编码哪些字符?
null 进去,出来仍然是 null。
空格进去,出来仍然是空格,不会被编码成 。
' 进去,出来仍然是 '。
& 进去,出来是:&
< 进去,出来是:<
> 进去,出来是:>
" 进去,出来是:"
所以,如果我们不希望引入 System.Web 的话,需要手写一个 HtmlEncode 的话,可以这样写:
private static string HtmlEncode(string s) { if (string.IsNullOrEmpty(s)) { return s; } return s.Replace("&", "&").Replace("<", "<").Replace(">", "gt;").Replace("\"", """); }
注意,& 要最先替换。
相关阅读