visual studio 配置 asp.net core razor .shtml文件类型和包含,支持跨平台通用

浪淘沙1年前后端346

自己在 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();


相关文章

文件上传

@page @model xxtsoft.Pages.uploadModel @{    } <h1>@ViewData["Title...

StringBuilder 简单写法

   public StringBuilder Sb { get; set; } = ne...

asp.net core 图片左下角 加水印

using SixLabors.Fonts; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Drawi...

asp.net core ZipDeploy iis发布 忽略某一件文件夹被删除

  services.AddZipDeploy(o => o.IgnorePathStarting("wwwroot/")); //iis发布...

asp.net core 压缩文件包

一、压缩类  #region 文件压缩  /**********调用示例*************   *   ...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。