在非 Sdk.Web 项目中使用 IRazorViewEngine 呈现 Razor 页面时出现 CompilationFailedException

CompilationFailedException when using IRazorViewEngine in non Sdk.Web projects to render Razor pages

我正在尝试在控制台应用程序 <Project Sdk="Microsoft.NET.Sdk">(而不是 <Project Sdk="Microsoft.NET.Sdk.Web">)中使用 IRazorViewEngine 在内存中呈现 .cshtml 页面。我在 ServiceProvider 中注册了每个需要的依赖项。在调用以下行时,我得到一个 CompilationFailedException:

_viewEngine.GetView(directory, name, true); 

异常:

Microsoft.AspNetCore.Mvc.Razor.Compilation.CompilationFailedException: One or more compilation failures occurred:
kmcajniq.bah(4,20): error CS0400: The type or namespace name 'Microsoft' could not be found in the global namespace (are you missing an assembly reference?)
kmcajniq.bah(5,19): error CS0400: The type or namespace name 'Microsoft' could not be found in the global namespace (are you missing an assembly reference?)
kmcajniq.bah(4,82): error CS0518: Predefined type 'System.Type' is not defined or imported
kmcajniq.bah(4,115): error CS0518: Predefined type 'System.String' is not defined or imported
kmcajniq.bah(4,132): error CS0518: Predefined type 'System.String' is not defined or imported
kmcajniq.bah(5,81): error CS0518: Predefined type 'System.String' is not defined or imported

和其他更多缺失的 SystemMicrosoft 类型。

但是,当我将项目 sdk 更改为 Microsoft.NET.Sdk.Web 时一切正常。

什么是 Microsoft.NET.Sdk 缺少 Microsoft.NET.Sdk.Web 的功能,Razor 渲染有效?

问题是,RazorViewEngine 需要编译上下文才能在 运行 时间内编译 Razor 页面。此默认设置在 Microsoft.NET.Sdk 中设置为 false,而在 Microsoft.NET.Sdk.Web 中设置为 true

要解决此问题,需要将以下 属性 添加到 .csproj 文件并设置为 true

<PropertyGroup>
    <PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>

可在此处找到有关差异的其他信息