我可以为具有相同扩展名(在同一文件夹中)的不同文件设置不同的 MIME 类型映射吗?

Can I have different MIME type mappings for different files with the same extension (in the same folder)?

简介

我像往常一样为静态文件配置 MIME,就像这样(效果很好,请继续阅读,以便您找到实际问题):

var defaultStaticFileProvider = new PhysicalFileProvider(Path.Combine(webHostEnvironment.ContentRootPath, "content"));
var contentTypeProvider = new FileExtensionContentTypeProvider();            
var defaultStaticFilesRequestPath = "/content";
// This serves static files from the 'content' directory.
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = defaultStaticFileProvider,
    ServeUnknownFileTypes = false,
    RequestPath = defaultStaticFilesRequestPath,
    ContentTypeProvider = contentTypeProvider
});

前面的代码默认将 .json 扩展映射到 application/json。工作正常。

问题

我想要的是将该映射更改为 application/manifest+json 但仅针对一个文件:manifest.json

所以,我尝试添加另一个这样的配置(不起作用):

// Add custom options for manifest.json only.
var manifestContentTypeProvider = new FileExtensionContentTypeProvider();
manifestContentTypeProvider.Mappings.Clear();
manifestContentTypeProvider.Mappings.Add(".json", "application/manifest+json");
var manifestStaticFileProvider = new PhysicalFileProvider(Path.Combine(webHostEnvironment.ContentRootPath, "content/en/app"));
var manifestStaticFileRequestPath = "/content/en/app/manifest.json";
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = manifestStaticFileProvider,
    ServeUnknownFileTypes = false,
    RequestPath = manifestStaticFileRequestPath,
    ContentTypeProvider = manifestContentTypeProvider
});

澄清一下,我在上一个代码之后添加了上面的代码。

希望问题足够清楚,我会查看评论,提出编辑提示以使其变得更好。

StaticFileOptions class 有一个 OnPrepareResponse 属性,您可以向其分配 Action 以更改 HTTP 响应 headers.

来自documentation

Called after the status code and headers have been set, but before the body has been written. This can be used to add or change the response headers.

Action 中,您检查 manifest.json 文件并 set/change content-type header 相应。该操作有一个 StaticFileResponseContext 输入参数,可以访问 HttpContextFile.

var options = new StaticFileOptions
{
    OnPrepareResponse = staticFileResponseContext =>
    {
        var httpContext = staticFileResponseContext.Context;

        // Request path check:
        if (httpContext.Request.Path.Equals("/content/en/app/manifest.json", StringComparison.OrdinalIgnoreCase))
        // or file name only check via: 
        // if (staticFileResponseContext.File.Name.Equals("manifest.json", StringComparison.OrdinalIgnoreCase))
        {
            httpContext.Response.ContentType = "application/manifest+json"
        }
    },
    // Your other custom configuration
    FileProvider = defaultStaticFileProvider,
    ServeUnknownFileTypes = false,
    RequestPath = defaultStaticFilesRequestPath
};

app.UseStaticFiles(options);