WebUtility.HtmlDecode replacement in .NET Core

I need to decode HTML characters in .NET Core (MVC6). It looks like .NET Core doesn't have WebUtility.HtmlDecode function which everybody used for that purpose before. Is there a replacement exist in .NET Core?


Solution 1:

This is in the System.Net.WebUtility class (Since .NET Standard 1.0) :

//
// Summary:
//     Provides methods for encoding and decoding URLs when processing Web requests.
public static class WebUtility
{
    public static string HtmlDecode(string value);
    public static string HtmlEncode(string value);
    public static string UrlDecode(string encodedValue);
    public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count);
    public static string UrlEncode(string value);
    public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count);
}

Solution 2:

This is in Net Core 2.0

using System.Text.Encodings.Web;

and call it:

$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(link)}'>clicking here</a>.");

UPDATE: Also in .Net Core 2.1:

using System.Web;

HttpUtility.UrlEncode(code)
HttpUtility.UrlDecode(code)

UPDATE: Also works from .NET Core 3.1 up to .NET 5 and .NET 6.

Solution 3:

I've found the HtmlDecode function in the WebUtility library to work.

System.Net.WebUtility.HtmlDecode(string)

Solution 4:

You need add reference System.Net.WebUtility.

  • It's already included in .Net Core 2 (Microsoft.AspNetCore.All)

  • Or you can install from NuGet - preview version for .Net Core 1.

So example, your code will be look like the below

public static string HtmlDecode(this string value)
{
     value = System.Net.WebUtility.HtmlDecode(value);
     return value;
}