jmoreno
jmoreno

Reputation: 13561

Differences between different .net framework HtmlEncode methods

What differences, if any are there between:

System.Web.HttpUtility.HtmlEncode
System.Web.HttpServerUtility.HtmlEncode
System.Net.WebUtility.HtmlEncode

Both HttpUtility.HtmlEncode and HttpServerUtility.HtmlEncode say:

To encode or decode values outside of a web application, use the WebUtility class.

Which implies that there is a difference, but doesn't come out say so directly or say what the difference is, if there is one.

Upvotes: 2

Views: 333

Answers (1)

Liam
Liam

Reputation: 29674

If you dig though the source code you can follow easily enough.

System.Web.HttpUtility.HtmlEncode

    /// <devdoc>
    ///    <para>
    ///       HTML encodes a string and returns the encoded string.
    ///    </para>
    /// </devdoc>
    public static String HtmlEncode(String s) {
        return HttpEncoder.Current.HtmlEncode(s);
    }

System.Web.HttpServerUtility.HtmlEncode

    /// <devdoc>
    ///    <para>
    ///       HTML
    ///       encodes a given string and
    ///       returns the encoded string.
    ///    </para>
    /// </devdoc>
    public string HtmlEncode(string s) {
        return HttpUtility.HtmlEncode(s);
    }

System.Net.WebUtility.HtmlEncode

    public static string HtmlEncode(string value) {
        if (String.IsNullOrEmpty(value)) {
            return value;
        }

        // Don't create string writer if we don't have nothing to encode
        int index = IndexOfHtmlEncodingChars(value, 0);
        if (index == -1) {
            return value;
        }

        StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
        HtmlEncode(value, writer);
        return writer.ToString();
    }

So System.Web.HttpServerUtility.HtmlEncode actually uses System.Web.HttpUtility.HtmlEncode. If you drill into HttpEncoder.Current.HtmlEncode(s); this has the following code:

    protected internal virtual void HtmlDecode(string value, TextWriter output) {
        WebUtility.HtmlDecode(value, output);
    }

Tl;Dr

So they all, ultimately, use System.Net.WebUtility.HtmlEncode. I guess the System.Web version are only there for backwards compatibillity. Hence the advice of using the System.Net version.

Upvotes: 3

Related Questions