gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:40:32 27 4
gpt4 key购买 nike

简介

我像往常一样为静态文件配置 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 类有一个 OnPrepareResponse您可以为其分配 Action 的属性以更改 HTTP 响应 header 。

来自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 文件并相应地设置/更改 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);

关于c# - 我可以为具有相同扩展名(在同一文件夹中)的不同文件设置不同的 MIME 类型映射吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72393502/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com