Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I globally set a custom HtmlEncoder to use in all Razor pages?

I want to set a custom HtmlEncoder as the default HtmlEncoder to be used in Asp.net Core Razor pages.

The RazorPageBase class does have a HtmlEncoder property which I can set on a single Razor page like this:

using System.Text.Encodings.Web;
using System.Text.Unicode;
@{
    HtmlEncoder = HtmlEncoder.Create(UnicodeRanges.All);
}

Then the HtmlEncoder is used on that page.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now the obvious thing to try is to apply this code to ‘ViewStart.cshtml’:

using System.Text.Encodings.Web;
using System.Text.Unicode;
@{
    Layout = "_Layout";
    HtmlEncoder = HtmlEncoder.Create(UnicodeRanges.All);
}

However, this does not work, it still uses the default HtmlEncoder (it compiles fine and it does pick up the Layout property).

This means, that to set the default HtmlEncoder for all pages, I have to include the code above to each and every Razor page, including each and every Partial page and of course "_Layout.cshtml".

I hope I have missed something.

How can I specify this on a global scale so it applies to all Razor pages?

>Solution :

In your app configuration, do the following:

[.NET 6 Program.cs]
builder.Services.Configure<WebEncoderOptions>(options =>
{
    options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
});

Or

[Pre-.NET 6 Startup.cs]
services.Configure<WebEncoderOptions>(options =>
{
    options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading