net核心服务器在内容类型响应头中不指定任何字符集的情况下提供静态文件



在我的blazor服务器应用程序(.NET6.0(中,我提供一些静态文件,并通过嵌入iframe来显示它们(因此浏览器直接处理文件类型,可以是图像、视频、声音、pdf等(

当它显示在iframe 中时,我注意到txt和html文件上强调字符的编码问题

我试着在iframe的头里面插入一个,但结果是相同的

我注意到对文件的http调用中有这些响应头

accept-ranges: bytes
content-encoding: br
content-type: text/plain
date: Thu, 23 Dec 2021 13:15:47 GMT
etag: "1d7f7ff334b008b"
last-modified: Thu, 23 Dec 2021 13:15:48 GMT
server: Kestrel
vary: Accept-Encoding

我很惊讶在内容类型标头中没有指定utf-8,我想知道这是否是我问题的根源?我期望类似的内容类型:text/plain;charset=utf-8

我试着在启动时使用StaticFileOptions来更改标题,但甚至在启动时将应用程序损坏

app.UseStaticFiles(new StaticFileOptions { 
});
//even doing this break the app, when the app start the file blazor.server.js finish in 404 on client side

所以我真的不能在这里做什么

th为我的静态文件提供服务,我以这种方式使用虚拟目录

app.UseFileServer(new FileServerOptions
{
FileProvider = new PhysicalFileProvider(Sys.Web.AppliIs.Path_Webdav),
RequestPath = new PathString("/" + Sys.Web.AppliIs.WEBDAV_FOLDER),
EnableDirectoryBrowsing = false
});

我注意到,当我直接用chrome打开链接时,我没有编码问题,它现在只在我的iframe中,我无法解释。

感谢您的帮助

我能够覆盖OnPrepareResponse来添加字符集,我不知道为什么,但我必须放入ISO字符集来解决编码问题

var lOptions = new FileServerOptions
{
FileProvider = new PhysicalFileProvider(Sys.Web.AppliIs.Path_Webdav),
RequestPath = new PathString("/" + Sys.Web.AppliIs.WEBDAV_FOLDER),
EnableDirectoryBrowsing = false,
};
lOptions.StaticFileOptions.OnPrepareResponse = (context) =>
{
var headers = context.Context.Response.Headers;
var contentType = headers["Content-Type"];
contentType += "; charset=ISO-8859-1";
headers["Content-Type"] = contentType;
};
app.UseFileServer(lOptions);

对我来说,这个主题很接近,但如果有人知道我为什么要指定这个字符集,我仍然很感兴趣。

最新更新