ASP.NET Core RC2 Can't Find Html Encoder Imple

2019-04-06 13:35发布

问题:

Can anyone show me an example of how to HTML encode text with the HtmlEncoder class in the System.Text.Encodings.Web namespace?

I'm converting an ASP.NET Core RC1 project to RC2. In the RC1 project I'm using the HtmlEncoder class in the Microsoft.Extensions.WebEncoders namespace. But there is no RC2 update for that.

According to this GitHub post Microsoft.Extensions.WebEncoders has been moved to System.Text.Encodings.Web. But the HtmlEncoder class in this new namespace is an abstract class and I can't find an implementation of it.

回答1:

It's got a few static methods to build encoders now.

Here's a simple example:

var value = "Hello<br> world";
var encoder = HtmlEncoder.Default;
var result = encoder.Encode(value); // "Hello&lt;br&gt; world"

Other methods include:

public static HtmlEncoder Create(TextEncoderSettings settings); 
public static HtmlEncoder Create(params UnicodeRange[] allowedRanges);