【问题标题】:In ASP.NET, how do I add a CORS header for only TTF files?在 ASP.NET 中,如何仅为 TTF 文件添加 CORS 标头?
【发布时间】:2012-07-22 10:49:12
【问题描述】:

我有一个带有显示外部页面的 iframe 的页面。外部页面配置为从我的服务器下载 CSS 文件。

在 CSS 中,我添加了一个 @font-face 选择器:

@font-face {
    font-family: "Special Font";
    src: url("<%= Request.Url.GetLeftPart(UriPartial.Authority) + "/fonts/specialfont.ttf" %>");
}

这会在 Chrome 中正常下载并显示字体,但在 Firefox 中,它会下载字体,但拒绝使用它。做一点研究表明这个问题是一个跨域策略问题。这里提到的解决方案之一:

http://enable-cors.org/

是启用 CORS 标头。但是,它提供的解决方案是站点范围的:

<?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <system.webServer>
            <httpProtocol>
                <customHeaders>
                    <add name="Access-Control-Allow-Origin" value="*" />
                </customHeaders>
            </httpProtocol>
        </system.webServer>
</configuration>

而我只想为 .TTF 文件启用它。有没有办法通过使用 HttpHandler 或其他方法来做到这一点?

【问题讨论】:

    标签: c# asp.net font-face cors


    【解决方案1】:

    您可以通过使用 web.config 中的location element 将配置规则限制到特定目录或文件来实现类似的目的。例如:

    <configuration>
      <location path="fonts/specialfont.ttf">
        <system.webServer>
           <httpProtocol>
              <customHeaders>
                 <add name="Access-Control-Allow-Origin" value="*" />
              </customHeaders>
           </httpProtocol>
        </system.webServer>
      </location>
    </configuration>
    

    尽管您可能希望为所有字体启用 CORS,例如&lt;location path="fonts"&gt;.

    this question 的答案还有几个location 的示例。

    【讨论】:

    • 谢谢,这有帮助!
    • 如果您在添加时开始收到 500 个错误,您可能希望在添加新的 CORS 值之前删除该字体路径的任何现有值,例如:&lt;remove name="Access-Control-Allow-Origin" /&gt; 在执行 &lt;add ...&gt; 之前
    猜你喜欢
    • 2017-05-31
    • 2013-08-09
    • 2017-11-09
    • 2019-12-20
    • 2020-12-06
    • 2017-05-23
    • 2020-04-26
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多