1

Should I use HttpUtility.HtmlEncode or write an extension method?

Pro for using HttpUtility.HtmlEncode is that other developers can instantly see and recognise what it's doing.

Pro for using an extension method is that it's less code to write everywhere and less noise.

So I guess I'm asking obvious readability vs tidier code.

2

Assuming you will call HttpUtility.HtmlEncoded() from your extension method (otherwise it's a no-no) and also that you will use a meaningful name to your method (otherwise you will just make code less clear). Given:

string someText = "This is some text";

Let's compare:

string htmlEncoded1 = someText.ToHtmlEncodedString();
string htmlEncoded2 = HttpUtility.HtmlEncode(someText);

Honestly I do not see any big improvement. Now let's introduce C# 6 static using feature:

string htmlEncoded1 = someText.ToHtmlEncodedString();
string htmlEncoded2 = HtmlEncode(someText);

I think it's clear which one is better. Also note that HttpUtility.HtmlEncode() has three overloaded methods and I usually consider a very bad practice to pollute object with useless extension methods.

Note that "...less code to write..." is not always and undoubtedly better. String conversions are an important and critical (both for performance and for security). If you name your method ToHtmlString() but - with help of Intellisense - you write ToString() you may have a potentially big bug latent in your code which may go unnoticed in a code review session.

0

The best advice is to not use HttpUtility.HtmlEncode. The problem is that this returns a string, which means that the type system cannot catch encoding mismatches.

The best solution is to have an HTML struct that represents strictly and only HTML, and then use instances of this to represent HTML, rather than strings. Then the compiler can assure you that you do not mismatch HTML and text.

Ideally, you should also use another struct for plain text.

0

You can have the best of both worlds by overriding the behavior HtmlEncode. This is accomplished by overriding the HttpEncoder class like so:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Util;
using System.Text;
using System.IO;

/// <summary>
/// Summary description for CustomHttpEncoder
/// </summary>
public class CustomHttpEncoder : HttpEncoder
{
    //
    // TODO: Add constructor logic here
    //
    public CustomHttpEncoder()
    {
    }

    protected override void HtmlEncode(string value, TextWriter output)
    {
        if (value != null) {
            MyHtmlEncode(value, output);
        }
    }

    protected override void HtmlAttributeEncode(string value, TextWriter output)
    {
        if (value != null) {
            MyHtmlEncode(value, output);
        }
    }

    private void MyHtmlEncode(string value, TextWriter output)
    {
        if (value != null) {
            string encodedValue = "";

            for (int i = 0; i <= value.Length - 1; i++) {
                byte[] asciiVal = Encoding.ASCII.GetBytes(value.Substring(i, 1));
                encodedValue += "&#" + asciiVal(0).ToString + ";";
            }

            output.Write(encodedValue);
        }
    }

}

After this, you just need to reference your overriding class in Web.config:

<system.web>
    <httpRuntime encoderType="CustomHttpEncoder" />

The Encoder class provided here is what I used on of my projects at work. Our pentesting suite is VERY picky with regards to output encoding, so the class above simply encodes every character in the string you give it. Feel free to remove the tin-foil hat and just have MyHtmlEncode() only encode certain characters.

  • 2
    I do not see in any way how this relates to the OP's question. – Jesse C. Slicer Jun 23 '16 at 16:07
  • As I understand it, OP is asking whether it is better to use HtmlEncode, or write an extension method that modifies the end result of HtmlEncode in some way. I am pointing out that it is possible to override HtmlEncode; allowing you to still call HtmlEncode, but have it use the logic that you define. Apologies if I have misunderstood the question. – Eren Jun 23 '16 at 17:25
  • 1
    I didn't downvote, just commented - but my understanding was use HtmlEncode as-is, or wrap it in an extension method for usage on strings "natively". – Jesse C. Slicer Jun 23 '16 at 17:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.