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

烈酒焚心 提交于 2020-02-05 14:56:12

问题


I am trying to use IRazorViewEngine in a console application <Project Sdk="Microsoft.NET.Sdk"> (not <Project Sdk="Microsoft.NET.Sdk.Web">) to render a .cshtml page in memory. I registered every needed dependency in the ServiceProvider. While calling the following line I get a CompilationFailedException:

_viewEngine.GetView(directory, name, true); 

Exception:

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

and other more missing System and Microsoft types.

However, when I'm changing the project sdk to Microsoft.NET.Sdk.Web everything works fine.

What is Microsoft.NET.Sdk missing what Microsoft.NET.Sdk.Web does, that Razor rendering works?


回答1:


The problem was, that the RazorViewEngine needs the compilation context to compile the Razor pages during run time. The default setting for this is in Microsoft.NET.Sdk set to false, while it is set in Microsoft.NET.Sdk.Web to true.

To fix the problem the following property needs to be added to the .csproj file and set to true:

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

Additional info about differences can be found here What are the differences between Microsoft.NET.Sdk and Microsoft.NET.Sdk.Web



来源:https://stackoverflow.com/questions/59969632/compilationfailedexception-when-using-irazorviewengine-in-non-sdk-web-projects-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!