visual studio 配置 asp.net core razor .shtml文件类型和包含,支持跨平台通用
自己在 ASP.NET Core 里写 Middleware 解析 SSI
自己在 ASP.NET Core 里写 Middleware 解析 SSI
// 先处理 .shtml 文件(SSI)
app.Use(async (context, next) =>
{
var path = context.Request.Path.Value;
if (!string.IsNullOrEmpty(path) && path.EndsWith(".shtml", StringComparison.OrdinalIgnoreCase))
{
var filePath = Path.Combine(env.WebRootPath, path.TrimStart('/'));
if (File.Exists(filePath))
{
var content = await File.ReadAllTextAsync(filePath);
// 处理 <!--#include file="xxx.html" -->
var regex = new Regex(@"<!--#include\s+file=""([^""]+)""\s*-->", RegexOptions.IgnoreCase);
content = regex.Replace(content, match =>
{
var includeFile = Path.Combine(Path.GetDirectoryName(filePath)!, match.Groups[1].Value);
if (File.Exists(includeFile))
{
return File.ReadAllText(includeFile);
}
else
{
return $"<!-- include {match.Groups[1].Value} not found -->";
}
});
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync(content);
return; // ⚠️ 一定要 return,避免走到 UseStaticFiles
}
}
await next();
});
// 其它静态文件(CSS, JS, 图片等)
app.UseStaticFiles();
