简体   繁体   中英

Why can't I use HttpServerUtility.HtmlEncode inside a class?

I am trying to use the following code:

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

I am getting the following error:

An object reference is required for the nonstatic field, method, or property.

Why can't I use HttpServerUtility.HtmlEncode inside a class?

You can use HttpUtility instead, which has a static method that does not depend on HttpContext .

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

More info on HttpUtility.HtmlEncode method on the MSDN .

HtmlEncode isn't a static method, and requires an instance of HttpServerUtility to call. Since HttpContext.Current.Server is a HttpServerUtility instance, you can instead use;

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

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

string myString = System.Net.WebUtility.HtmlEncode(my link & details);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM