Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is HtmlEncode in Asp.NET 5

I have a custom IHtmlHelper extension method that uses TagBuilder and returns an HtmlString. I can no longer pass tagBuiler.ToString() to the HtmlString constructor as that just returns the typename now.

I see I can use the tabBuiler.WriteTo(TextWriter, IHtmlEncoder) method but I don't know exactly how to get my hands on an object that implments IHtmlEncoder. I see encoders in both System.Text.Encodings.Web and Microsoft.Framework.WebEncoders. But the types in the two namespace don't seem to play well together.

like image 525
Keith Hill Avatar asked Nov 25 '15 19:11

Keith Hill


People also ask

What is HtmlEncode asp net?

HtmlEncode is a convenient way to access the HttpUtility. HtmlEncode method at run time from an ASP.NET application. Internally, HtmlEncode uses HttpUtility. HtmlEncode to encode strings. To encode or decode values outside of a web application, use the WebUtility class.

What is HtmlEncode C#?

HtmlEncode(Object)Converts an object's string representation into an HTML-encoded string, and returns the encoded string. public: static System::String ^ HtmlEncode(System::Object ^ value); C# Copy.

What is Server HtmlEncode?

The HTMLEncode method applies HTML encoding to a specified string. This is useful as a quick method of encoding form data and other client request data before using it in your Web application. Encoding data converts potentially unsafe characters to their HTML-encoded equivalent.

When should I use HtmlEncode?

Any time you are trying to output data that could include untrusted html, you should use HTMLENCODE . Encodes text and merge field values for use in HTML by replacing characters that are reserved in HTML, such as the greater-than sign ( > ), with HTML entity equivalents, such as > .


3 Answers

In ASP.NET Core RC2 you can find HtmlDecode in System.Net.WebUtility:

  • GitHub source of System.Net.WebUtility

In your project.json import dependency system.net.utilities

"dependencies": {
    "System.Text.Encodings.Web": "4.0.0-rc2-24027"
}
like image 52
Miroslav Holec Avatar answered Sep 28 '22 08:09

Miroslav Holec


Just use System.Net.WebUtility.HtmlEncode or decode as:

System.Net.WebUtility.HtmlEncode() System.Net.WebUtility.HtmlDecode()

like image 27
Long Field Avatar answered Sep 28 '22 10:09

Long Field


As for RC1 update 1, here is how it is done:

using System.Text.Encodings.Web;

...

HtmlEncoder.Default.Encode("...");
like image 23
Greg Ennis Avatar answered Sep 28 '22 09:09

Greg Ennis