C# TemplateService.Parse给出了;模拟的令牌无效-无法复制;使用匿名模型和缓存名称时

C# TemplateService.Parse给出了;模拟的令牌无效-无法复制;使用匿名模型和缓存名称时,c#,razor,razorengine,C#,Razor,Razorengine,我使用RazorEngine生成HTML电子邮件(没有ASP.NET MVC)。当我使用强类型视图或匿名对象作为模型时,它工作得很好: Layout.cshtml C#代码段 然后我给了它一个缓存名称,正如在下面的 它在强类型对象上运行良好,但在匿名对象上,我从第二次运行时就开始接收此消息: 模拟的令牌无效-无法复制 我如何解决这个问题,并且仍然对模型使用匿名对象 我见过一些建议将匿名对象转换为ExpandoObject的解决方案(,),但如果可能的话,我想避免这种情况。阅读RazorEngin

我使用RazorEngine生成HTML电子邮件(没有ASP.NET MVC)。当我使用强类型视图或匿名对象作为模型时,它工作得很好:

Layout.cshtml

C#代码段

然后我给了它一个缓存名称,正如在下面的

它在强类型对象上运行良好,但在匿名对象上,我从第二次运行时就开始接收此消息:

模拟的令牌无效-无法复制

我如何解决这个问题,并且仍然对模型使用匿名对象


我见过一些建议将匿名对象转换为
ExpandoObject
的解决方案(,),但如果可能的话,我想避免这种情况。

阅读RazorEngine文档后,我在他们的网站上找到了一些示例,展示了如何使用
引擎.Razor
。最简单的方法是:

var html = Engine.Razor.RunCompile(
    template,
    nameof(Properties.Resources.ContractList),
    null,
    model
);
这就解决了问题。请注意,他们不建议使用上述格式,因为每次在内部它都会调用
AddTemplate
,并且当您对不同的模板使用相同的
cache\u name
时,它会引发异常。相反,他们建议在启动时进行预编译:

// Once at startup (not required when using an ITemplateManager which knows how to
// resolve cache_name)
Engine.Razor.AddTemplate(cache_name, razorTemplate)
// On startup
Engine.Razor.Compile(
    cache_name, 
    typeof(MyModel) /* or model.GetType() or null for 'dynamic'*/
)

// instead of the Razor.Parse call
var result = Engine.Razor.Run(
    cache_name,
    typeof(MyModel), /* or model.GetType() or null for 'dynamic'*/
    model
)
templateService.Parse(template, model, null, nameof(Properties.Resources.ContractList));
var html = Engine.Razor.RunCompile(
    template,
    nameof(Properties.Resources.ContractList),
    null,
    model
);
// Once at startup (not required when using an ITemplateManager which knows how to
// resolve cache_name)
Engine.Razor.AddTemplate(cache_name, razorTemplate)
// On startup
Engine.Razor.Compile(
    cache_name, 
    typeof(MyModel) /* or model.GetType() or null for 'dynamic'*/
)

// instead of the Razor.Parse call
var result = Engine.Razor.Run(
    cache_name,
    typeof(MyModel), /* or model.GetType() or null for 'dynamic'*/
    model
)