RenderSection()是否可以在ASP.NET Core的<environment>标记帮助器内工作?

gro*_*kky 4 c# asp.net razor tag-helpers asp.net-core

布局有这个:

<!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>
Run Code Online (Sandbox Code Playgroud)

视图有这个:

@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>
Run Code Online (Sandbox Code Playgroud)

当标签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()在其中?

Jah*_*han 9

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


gro*_*kky 5

这个答案是由于@ 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>
Run Code Online (Sandbox Code Playgroud)

因此,这些部分始终是定义的,因此子视图永远不会抛出。