首页 > 解决方案 > 尝试使用 Razor 引擎解析模板时,来自程序集“mscorlib”的“System.Security.Principal.WindowsImpersonationContext”错误

问题描述

我必须创建一个能够发送电子邮件的 Asp.Net Web Api。我设法发送了电子邮件,但仅使用本地存储在变量中的简单模板。下一步是从外部文件渲染模板,如下所示:

            string filePath = @"C:\Data\EmailClient\EmailClient\EmailClient\EmailTemplate\ReceiptTemplate.cshtml";
            var config = new TemplateServiceConfiguration
                             {
                                 TemplateManager = new ResolvePathTemplateManager(new[] { "EmailTemplates" }),
                                 DisableTempFileLocking = true
                             };
            Engine.Razor = RazorEngineService.Create(config);

            if (File.Exists(filePath))
            {
                emailHtmlBody = Engine.Razor.RunCompile(filePath, null, email);
                mail.Body = emailHtmlBody;
            }

问题是,当剃刀引擎尝试解析模板时,会出现以下错误:

"Could not load type 'System.Security.Principal.WindowsImpersonationContext' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'."

我试图从字符串中解析模板,我也被同样的错误阻止了。

标签: .netasp.net-web-apirazorengine

解决方案


你可能会看到

<PackageReference Include="RazorEngine" Version="3.10.0" />  

或类似的 .csproj 文件,当你真正需要的是

<PackageReference Include="RazorEngine.Netcore" Version="3.1.0" />

所以,

$ dotnet remove package RazorEngine
$ dotnet add package RazorEngine.Netcore --version 3.1.0

(或与版本更新类似)看起来好像是答案
[Matt 的答案有一个“建议的编辑队列已满”标志]


推荐阅读