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.
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?
CodePudding user response:
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);
});