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

3

介绍

我通常会配置静态文件的 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
});

为了澄清,我已经在之前的代码后面添加了上面的代码。

希望问题足够清楚,无论如何,我将检查评论以提出编辑建议,使其更好。


1
每个附件的MIME文件都以两个破折号开始的新行开头。请参阅MSDN示例:https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/aa563375(v=exchg.140)?force_isolation=true - jdweng
1个回答

1

StaticFileOptions类有一个 OnPrepareResponse 属性,可以将一个Action分配给它,以更改HTTP响应头。

文档中:

在状态码和头部设置后被调用,但写入正文之前。这可用于添加或更改响应头。

在该Action中,您可以检查是否存在manifest.json文件,并相应地设置/更改content-type头部。该操作具有一个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);

这看起来非常不错,我想我很快就会接受你的答案,谢谢。 - Raudel Ravelo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接