如何在 .NET Core 中对没有文件扩展名的文件设置 MIME 类型?



我得到了一些文件来使用WebAssembly模块,应该将其设置为作为应用程序/八位字节流加载。

我已经找到了在 Startup 中设置 MIME 类型的文档.cs并使其适用于 WebAssembly 模块本身。

不幸的是,还有其他三个文件应该作为应用程序/八位字节流加载,这些文件没有文件扩展名,例如file1-shard1.我尝试直接使用wilcards解决它们,但它们仍然在Firefox的"网络"选项卡中显示为Type = html。

有谁知道我如何正确设置这些文件的MIME类型?

// Set up FileExtension Content Provider for Web Assembly
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".wasm"] = "application/wasm";
// Set up MIME type for shard files
provider.Mappings["file1-shard1"] = "application/octet-stream";
provider.Mappings["*shard1*"] = "application/octet-stream";
provider.Mappings[".*"] = "application/octet-stream";
provider.Mappings["."] = "application/octet-stream";
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = provider
});

你不能使用FileExtensionContentTypeProvider执行此操作,因为如果文件没有扩展名,它会在内部失败。

您要么需要实现自定义IContentTypeProvider,要么设置StaticFileOptions.DefaultContentType

感谢雅科夫在这方面的领导。除了 DefaultContentType 之外,还需要告知应用服务在包含这些文件的文件夹中提供 UnknownFileType。

在下面的代码中,app.UseStaticFiles();是使 wwwroot 文件夹正常工作的现有代码。此代码应添加到"启动"中.cs

然后,我为 WebAssembly 文件设置映射。然后,这将用于应用的新版本。对包含默认内容类型和 ServeUnknownFileTypes 的特定文件夹使用静态文件((。

它并不完美,因为存在一些与ServeUnknown文件类型相关的安全风险,但在这种情况下,它仅限于单个文件夹。

// Default options for wwwroot
app.UseStaticFiles();
// Set up FileExtension Content Provider for Web Assembly
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".wasm"] = "application/wasm";
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = provider,
ServeUnknownFileTypes = true,
DefaultContentType = "application/octet-stream",
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/WebAssemFiles")),
RequestPath = "/WebAssemFiles"
});

最新更新