关于在非Sdk.Web项目中使用IRazorViewEngine渲染Razor页面时的c#: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

1
_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

1
2
3
<PropertyGroup>
    <PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>

有关差异的其他信息,可以在这里找到。Microsoft.NET.Sdk和Microsoft.NET.Sdk.Web

之间有什么区别?