Web核心中的WebUtility.HtmlDecode替换

sib*_*vic 72 .net c# asp.net-core-mvc asp.net-core

我需要在.NET Core(MVC6)中解码HTML字符.看起来.NET Core没有WebUtility.HtmlDecode函数,之前每个人都用它..NET Core中是否存在替代品?

Sco*_*man 96

这是在System.Net.WebUtility课堂上:

//
// 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);
}
Run Code Online (Sandbox Code Playgroud)

  • 对于.NET Core 1.1,请使用https://www.nuget.org/packages/Microsoft.AspNetCore.WebUtilities (8认同)
  • 对于.NET Core 2.1,请参阅下面的Gerardo的回复,无需安装另一个nuget包. (3认同)

Ger*_*lez 26

这是在Net Core 2.0中

using System.Text.Encodings.Web;
Run Code Online (Sandbox Code Playgroud)

并称之为:

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

更新:同样在.Net Core 2.1中:

using System.Web;

HttpUtility.UrlEncode(code)
HttpUtility.UrlDecode(code)
Run Code Online (Sandbox Code Playgroud)


小智 13

我发现WebUtility库中的HtmlDecode函数可以正常工作.

System.Net.WebUtility.HtmlDecode(string)
Run Code Online (Sandbox Code Playgroud)


小智 5

您需要添加引用System.Net.WebUtility

  • 它已经包含在 .Net Core 2 ( Microsoft.AspNetCore.All)

  • 或者您可以从NuGet安装- .Net Core 1 的预览版。

例如,您的代码将如下所示

public static string HtmlDecode(this string value)
{
     value = System.Net.WebUtility.HtmlDecode(value);
     return value;
}
Run Code Online (Sandbox Code Playgroud)

  • 或者只是调用`WebUtility.HtmlDecode` 没有理由将它包装在扩展方法中...... (3认同)

Vic*_*aci 2

HtmlDecode并且大部分*Decode方法没有移植到CoreFx。只有*Encode方法可用。

以下是今天提供的内容: https: //github.com/dotnet/corefx/blob/1dfe38aeb2811fbbd6d4de36d210f060e80d50a6/src/System.Text.Encodings.Web/src/System/Text/Encodings/Web/HtmlEncoder.cs