Alex Rivera | Logout

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

Asked 2012-04-21T16:04:15.237
13

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?

Edit
Report

2 Answers

34

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.

answered 2012-04-21T16:15:54.347
29

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");
answered 2012-04-21T16:08:48.773

Your Answer