RenderSection() 是否在 ASP.NET Core 的 <environment> 标签助手中工作?

Does RenderSection() work inside ASP.NET Core's <environment> tag-helper?

布局是这样的:

<!DOCTYPE html>
<html>
<head>
  <environment names="Development">@RenderSection("devCss", required: false)</environment>
  <environment names="Staging,Production">@RenderSection("staproCss", required: false)</environment>
</head>
<body>
  @RenderBody()
  <environment names="Development">@RenderSection("devJs", required: false)</environment>
  <environment names="Staging,Production">@RenderSection("staproJs", required: false)</environment>
</body>
</html>

视图有这个:

@section devCss { <link rel="stylesheet" href="foo.css" asp-append-version="true" /> }
@section staproCss { <link rel="stylesheet" href="foo.min.css" asp-append-version="true" /> }
@section devJs {}
@section staproJs {}

<h1>hello</h1>

RenderSection()<environment> 标签之外时,一切正常。

在内部时,如上例所示,它失败并出现无用的错误 InvalidOperationException: The following sections have been defined but have not been rendered by the page at '_Layout.cshtml': 'staproCss, staproJs'. To ignore an unrendered section call IgnoreSection("sectionName").

这显然没有意义,因为所有部分都已定义。它抱怨一些,而不是其他人。

<environment> 标签助手是否允许 RenderSection() 在其中?

不,环境标签用于根据 ASPNET_ENV 环境变量定义的环境呈现不同的 HTML。例如,与生产环境相比,一组不同的 CSS 定义可用于开发环境。

这个 link 也可能有帮助: A Complete Guide to the MVC 6 Tag Helpers

您可以在您的网站逻辑中使用环境变量值,如此处所示。

有关详细信息,请参阅此 link:Working with Multiple Environments

此回答感谢@user2818985 的评论。

未定义的环境不会发出其中的内容。这意味着它不会发出 RenderSection() 调用。这意味着该视图将定义一个不存在的 section foo { ... }。哪个失败了,因此例外。

为了完成最初的目标,我更新了布局:

@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment _env
<!DOCTYPE html>
<html>
<head>
    <environment names="Development">
        @RenderSection("devCss", required: false)
    </environment>
    <environment names="Staging,Production">
        @RenderSection("staproCss", required: false)
    </environment>
    @if (_env.EnvironmentName == "Development" && IsSectionDefined("staproCss"))
    {
        IgnoreSection("staproCss"); 
    }
    @if (_env.EnvironmentName == "Staging,Production" && IsSectionDefined("devCss"))
    { 
        IgnoreSection("devCss"); 
    }
</head>
<body>
    @RenderBody()
    <environment names="Development">
        @RenderSection("devJs", required: false)
    </environment>
    <environment names="Staging,Production">
        @RenderSection("staproJs", required: false)
    </environment>
    @if (_env.EnvironmentName == "Development" && IsSectionDefined("staproJs")) 
    { 
        IgnoreSection("staproJs"); 
    }
    @if (_env.EnvironmentName == "Staging,Production" && IsSectionDefined("devJs")) 
    { 
        IgnoreSection("devJs"); 
    }
</body>
</html>

所以这些部分总是被定义的,所以子视图永远不会抛出。

只需在 </body> 标签末尾添加 @RenderSection("Scripts", required: false)