System.Text.Encodings.Web
The namespace contains a base class that represents web encoders, subclasses that represent HTML, JavaScript, and URL character encoding, as well as classes that represent filters that only allow the encoding of specific characters, character ranges, or code points.
[ Definition from Microsoft ]
This namespace has five classes for encoding handling of different objects.
Five Classes
HtmlEncoder |
Represents HTML character encoding. |
JavaScriptEncoder |
Represents JavaScript character encoding. |
TextEncoder |
The base class for web encoders. |
TextEncoderSettings |
Represents a filter that only allows specific Unicode code points. |
UrlEncoder |
Represents URL character encoding. |
HtmlEncoder
HtmlEncoder has the following methods along with HtmlEncoder.Default
Create, Default, Equals, ReferenceEquals
Specifically,
Typically, we only use HtmlEncoder.Default.Encode()
Usage of HtmlEncoder.Default.Encode()
Microsoft's official definition
Using HtmlEncoder.Default.Encode
prevents malicious input (i.e., JavaScript) from damaging the application.
This means that certain symbols, Chinese characters, etc., will be encoded so that they do not appear in their original form.
Encoding
Assume there is a news system where users can comment on news articles. If a user posts a malicious JavaScript code in a comment.
If the system does not handle this, when other users open this news article, the comment from that user will load and execute the malicious JavaScript code.
HtmlEncoder.Default.Encode can convert special symbols (including Chinese characters) in a string to their encoded format.
Example
Create a new ASP.NET Core application.
Add the following method to the controller.
Compile and run, then open the view.
You can see that the string in view a is output in its original text, while the encoded text in view b encodes special symbols.
Where there is encoding, there is also decoding, which will not be elaborated here.
The usage of the other four classes is generally similar and will not be elaborated further.
Please refer to
https://docs.microsoft.com/zh-cn/dotnet/api/system.text.encodings.web?view=netcore-2.0
文章评论