RazorEngine “Unable to compile template” Error

独自空忆成欢 提交于 2019-12-13 03:59:51

问题


I'm using the following code to build and send an email using RazorEngine.

//build email using template.
string template = File.OpenText(EmailTemplatePath).ReadToEnd();
OrganizationInviteEmailTemplate model = new OrganizationInviteEmailTemplate()
{
    FirstName = Invitation.FirstName,
    LastName = Invitation.LastName,
    Message = Message,
    OrganizationName = Invitation.Organization.OrganizationName,
    ConfirmUrl = string.Format(ConfirmUrlTemplate, Invitation.InviteCode)
};
string body = Razor.Parse(template, model);

//email the invitation.
MailMessage message = new MailMessage();
message.To.Add(Invitation.Email);
message.Subject = "Invitation From " + Invitation.Organization.OrganizationName;
message.Body = body;
message.IsBodyHtml = true;

SmtpClient client = new SmtpClient();
client.Send(message);

The template is below:

 <html>
     <head>
     </head>
     <body>
         <h3>@Model.OrganizationName has invited you to be part of their organization</h3>

         <p>
         Hi @Model.FirstName,
         </p>

         .....etc......
     </body>
 </html>

I get the "Unable to compile template" error 9 times out of 10 and then it will work once after I adjust the template by removing Model. and/or adjusting the code to use Parse instead, but then it will go right back to not working. It's like something is caching a piece of code briefly or something.

I'm using the RazorEngine.dll included with RazorJS, version 2.1.4113.149. Maybe that's the issue. Going to try this library or Postal next since this is taking way too much time already. Or just hard code the damn thing.


回答1:


Unless you want to code it all by yourself, it will be more easy to install a nuget package like MvcMailer.




回答2:


Aren't you missing the @model declaration at the top of your template?



来源:https://stackoverflow.com/questions/5756507/razorengine-unable-to-compile-template-error

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