2012-04-21 69 views

回答

23

HtmlEncode不是一種靜態方法,需要調用HttpServerUtility的實例。由於HttpContext.Current.Server是一個HttpServerUtility實例,因此可以改爲使用;

string myString = HttpContext.Current.Server.HtmlEncode("my link & details"); 
+0

這是一樣的。 HttpServerUtility.HtmlEncode只是轉發給HttpUtility.HtmlEncode – Rolf 2015-12-12 13:52:36

27

您可以使用HttpUtility代替,它具有不依賴於HttpContext的靜態方法。

string myString = HttpUtility.HtmlEncode("my link & details"); 

More info on HttpUtility.HtmlEncode method on the MSDN

+1

布爾耶!投票.... – granadaCoder 2012-05-23 19:41:11

+0

Upvoted!我有同樣的問題,但沒有使用HttpContext,所以這是我的解決方案。 – 2015-01-28 14:45:44

+2

這是更好的方式,你永遠不知道什麼時候你的HttpContext.Current將會是null! – 2015-02-13 20:11:27

2

如果您使用.NET 4.5,此實用程序是System.Net.WebUtility的一部分。

string myString = System.Net.WebUtility.HtmlEncode(my link & details); 
相關問題