如何从 owin FileServer 提供 woff2 文件

How to serve woff2 files from owin FileServer

自 font awesome 4.3 以来,他们将字体添加为 woff2 格式。

我在尝试通过 owin 提供此文件时遇到 404ed:

app.UseFileServer(new FileServerOptions() {
    RequestPath = PathString.Empty,
    FileSystem = new PhysicalFileSystem(@"banana")
});

如何在 owin 中通过文件服务器提供 woff2 mime 类型文件?

两种可能:

  • 提供所有类型的文件:
var options = new FileServerOptions() {
    RequestPath = PathString.Empty,
    FileSystem = new PhysicalFileSystem(@"banana")
};

options.StaticFileOptions.ServeUnknownFileTypes = true;

app.UseFileServer(options);
  • 添加 woff2 mime 类型:
var options = new FileServerOptions() {
    RequestPath = PathString.Empty,
    FileSystem = new PhysicalFileSystem(@"banana")
};

((FileExtensionContentTypeProvider)options.StaticFileOptions.ContentTypeProvider)
    .Mappings.Add(".woff2", "application/font-woff2");

app.UseFileServer(options);

第二个选项似乎不那么优雅,但仍然是最好的。阅读 why mime types are important.

您可以使用继承来避免不太好的转换:

FileServerOptions options = new FileServerOptions
{
    StaticFileOptions =
    {
        ContentTypeProvider = new CustomFileExtensionContentTypeProvider(),
    }
};

哪里

private class CustomFileExtensionContentTypeProvider : FileExtensionContentTypeProvider
{
    public CustomFileExtensionContentTypeProvider()
    {
        Mappings.Add(".json", "application/json");
        Mappings.Add(".mustache", "text/template");
    }
}