【问题标题】:Serving ISO-8859-1 and UTF-8 files from ASP.NET从 ASP.NET 提供 ISO-8859-1 和 UTF-8 文件
【发布时间】:2011-03-07 17:32:09
【问题描述】:

我们有一个包含数千个静态 html 文件的大型网站。其中一些是 ISO-8859-1,另一些是 UTF-8(有和没有字节顺序标记)。

web.config 文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <globalization requestEncoding="utf-8" responseEncoding="utf-8" fileEncoding="utf-8" />
  </system.web>
</configuration>

如果我将 fileEncoding 更改为 "ISO-8859-1" 它适用于 ISO-8859-1 和 UTF-8如果有字节顺序标记。我们试图避免手动检查字节顺序标记并将其添加到没有它们的文件中。有没有办法做到这一点?

文件具有字符集元标记。我们可以让服务器读取它来确定文件编码吗?

编辑

如果我删除到 aspnet_isapi.dll 的通配符应用程序映射,则可以正确提供文件。有没有办法让通配符匹配除 .html 之外的所有内容?

【问题讨论】:

  • 你可以运行一个脚本将所有页面转换为 UTF-8
  • 我们有数百名不断更改文件的贡献者。跟上每个文件更改将是一个问题。
  • 听起来您需要一个 CMS,在该 CMS 中,用户无法发布标题标签或任何标题,因此无法设置编码。
  • @Thomas。我们有一个,但静态文件来自 CMS 之前的日子,最终会被转换。

标签: .net asp.net character-encoding iis-6


【解决方案1】:

您可以自动检查文件以查看它们是否包含所述字符/它们是否为 utf-8。

这是一段代码,在谷歌搜索该目的时弹出found here

System.Text.Encoding enc = null; 
System.IO.FileStream file = new System.IO.FileStream(filePath, 
    FileMode.Open, FileAccess.Read, FileShare.Read); 
if (file.CanSeek) 
{ 
    byte[] bom = new byte[4]; // Get the byte-order mark, if there is one 
    file.Read(bom, 0, 4); 
    if ((bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) || // utf-8 
        (bom[0] == 0xff && bom[1] == 0xfe) || // ucs-2le, ucs-4le, and ucs-16le 
        (bom[0] == 0xfe && bom[1] == 0xff) || // utf-16 and ucs-2 
        (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff)) // ucs-4 
    { 
        enc = System.Text.Encoding.Unicode; 
    } 
    else 
    { 
        enc = System.Text.Encoding.ASCII; 
    } 

    // Now reposition the file cursor back to the start of the file 
    file.Seek(0, System.IO.SeekOrigin.Begin); 
} 
else 
{ 
    // The file cannot be randomly accessed, so you need to decide what to set the default to 
    // based on the data provided. If you're expecting data from a lot of older applications, 
    // default your encoding to Encoding.ASCII. If you're expecting data from a lot of newer 
    // applications, default your encoding to Encoding.Unicode. Also, since binary files are 
    // single byte-based, so you will want to use Encoding.ASCII, even though you'll probably 
    // never need to use the encoding then since the Encoding classes are really meant to get 
    // strings from the byte array that is the file. 

    enc = System.Text.Encoding.ASCII; 
} 

【讨论】:

  • 那只会检测带有字节顺序标记的 UTF-8。许多文件没有它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-24
  • 2018-07-06
  • 2011-09-23
相关资源
最近更新 更多