MVC 3剃须刀页EN codeD为UTF-8所示的连接codeD字符 [英] MVC 3 Razor page encoded as utf 8 shows encoded characters

查看:115
本文介绍了MVC 3剃须刀页EN codeD为UTF-8所示的连接codeD字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的VirtualPathProvider这需要源$ C ​​$ C从我的数据库作为一个纯字符串和连接codeS作为UTF8。

I have a VirtualPathProvider which takes source code from my DB as a plain string and encodes it as UTF8.

例如:

public override Stream Open()
{
  MemoryStream result = new MemoryStream();

  result = new MemoryStream(Encoding.UTF8.GetBytes(_sourceCode));

  return result;
}

然后我有有它的字符集布局母版页UTF-8

I then have a layout master page which has its charset as UTF 8

<meta charset="utf-8">

母版页,然后调用 @RenderBody()这得到我的VirtualPathProvider页面并输出到浏览器中。

The master page then calls @RenderBody() which gets my VirtualPathProvider page and outputs it to the browser.

问题是,它与它的EN codeD字符输出的页面:

The problem is that it is outputting the page with its encoded characters:

wünschte成为wünschte

wünschte becomes wünschte

我在做什么错了?

TLDR:

我要wünschte显示,而不是wünschte。从DB的纯字符串是wünschte,但一旦它来自内存流到我的网页就变成wünschte。

I want wünschte to display instead of wünschte. The plain string from the DB is wünschte, but once it comes from the memory stream onto my page it becomes wünschte.

推荐答案

正如有人谁与今天这个挣扎着自己的的VirtualPathProvider 的实施,事实证明,剃刀的真正的希望字节顺序标记。您可以通过调用强制此获取preamble()

As someone who struggled with this today with his own VirtualPathProvider implementation, it turns out that Razor really wants the byte order mark. 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);
}

如果BOM表不存在,剃刀似乎默认为当前codePAGE而不是UTF8。上述固定对我来说。

If the BOM isn't there, Razor seems to default to the current codepage and not UTF8. The above fixed it for me.

在上面的例子中,你会替换 this.Template 我在执行与 _source code 在原来的问题。

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

这篇关于MVC 3剃须刀页EN codeD为UTF-8所示的连接codeD字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆