Utc 8 encoded MVC 3 Razor page shows encoded characters

I have a VirtualPathProvider that takes the source code from my DB as a simple string and encodes it as UTF8.

For instance:

public override Stream Open() { MemoryStream result = new MemoryStream(); result = new MemoryStream(Encoding.UTF8.GetBytes(_sourceCode)); return result; } 

Then I have the main page of the layout, which has its own encoding as UTF 8

 <meta charset="utf-8"> 

Then the master page calls @RenderBody() , which receives my VirtualPathProvider page and displays it in the browser.

The problem is that it displays a page with its encoded characters:

wünschte becomes wünschte

What am I doing wrong?

TL; DR:

I want wünschte to appear instead of wünschte. A simple line from the database is wünschte, but as soon as it comes from the memory stream to my page, it becomes wÃnchte.

+4
source share
1 answer

Like the one who struggled with this today with his own implementation of VirtualPathProvider , it turns out that Razor really wants to note the byte order. You can force this by calling GetPreamble() .

 using System.Linq; // for Concat() because I am lazy public override Stream Open() { var template = Encoding.UTF8 .GetBytes(this.Template); var buffer = Encoding.UTF8 .GetPreamble() .Concat(template) .ToArray(); return new MemoryStream(buffer); } 

If the specification is missing, Razor does not default to the current code page, not UTF8. The above fixed it for me.

In the above example, you replaced this.Template in my implementation with _sourceCode in the original question.

+5
source

All Articles