You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RazorEngineService.RunCompile编译报错:当前上下文中不存在名称'section'

错误原因

你用的第三方Razor渲染库RazorEngine本身没有内置对@section、@RenderSection语法的支持,这两个语法是ASP.NET MVC/Razor Pages框架自带的扩展功能,不属于原生Razor语法,脱离MVC框架单独调用RazorEngine时就会报「section不存在于当前上下文」的错误。

解决方案

方案1(推荐):更换支持section的渲染库

改用RazorLight库,这个库专门用于脱离ASP.NET框架的Razor模板渲染,原生支持布局、section的完整功能,适配你的场景成本最低。

方案2:不使用section,改用变量传递内容

如果要继续使用RazorEngine,可以放弃section写法,用动态变量传递样式等内容:

  1. 子布局_SubLayout.cshtml中修改定义:
@{ 
    Layout = "_MainLayout";
    // 把样式内容存到ViewBag里
    ViewBag.PageStyles = @"<style>
          .container { width: 50%; }
     </style>";
}

<div class="container"></div>
  1. 主布局_MainLayout.cshtml中直接输出变量,用@Raw防止HTML被转义:
<!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html charset=UTF-8" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700">
    <style>
        html,
        body {
            margin: 0 !important;
            padding: 0 !important;
            height: 100% !important;
            width: 100% !important;
        }
        @Raw(ViewBag.PageStyles)
    </style>
</head>
<html>
<body>
    @RenderBody()
</body>
</html>

方案3:自定义RazorEngine模板基类实现section功能

如果要保留section写法,需要自定义继承自TemplateBase的模板基类,自行实现DefineSection、RenderSection的逻辑,实现成本较高,仅适合复杂场景使用。

附加优化建议

你现有代码中每次调用RenderTemplate都会新建RazorEngineService实例,且用随机Guid作为模板Key,不会复用编译好的模板,会导致性能差、内存占用过高的问题,建议将RazorEngineService改成单例,模板Key用视图的相对路径作为唯一标识,复用编译结果。

内容的提问来源于stack exchange,提问作者iamrafael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 22:54:02