我的回答,使用来自here 的hannes neukermans 回答。
我需要在 MVC 项目中使用 RazorEngine 来发送包含存储在数据库中的 html 字符串的电子邮件,以便管理员用户可以编辑它们。
标准的 RazorEngine 配置不允许 @Html.Raw 工作。
在我的电子邮件类中,我设置了一个新的 Engine.Razor(引擎是静态的),其中包含 Hannes 推荐的类。我只需要 Raw 方法,但您显然可以添加其他方法:
你需要这些:
using RazorEngine;
using RazorEngine.Templating; // For extension methods.
using RazorEngine.Text;
using RazorEngine.Configuration;
这些是提供@Html 帮助器的类
public class HtmlSupportTemplateBase<T> : TemplateBase<T>
{
public HtmlSupportTemplateBase()
{
Html = new MyHtmlHelper();
}
public MyHtmlHelper Html { get; set; }
}
public class MyHtmlHelper
{
/// <summary>
/// Instructs razor to render a string without applying html encoding.
/// </summary>
/// <param name="htmlString"></param>
/// <returns></returns>
public IEncodedString Raw(string htmlString)
{
return new RawString(WebUtility.HtmlEncode(htmlString)); //you may not need the WebUtility.HtmlEncode here, but I did
}
}
然后我可以在我的电子邮件模板中使用 @Html.Raw 来合并可编辑的 html
public class Emails
{
public static TemplateServiceConfiguration config
= new TemplateServiceConfiguration(); // create a new config
public Emails()
{
config.BaseTemplateType = typeof(HtmlSupportTemplateBase<>);// incorporate the Html helper class
Engine.Razor = RazorEngineService.Create(config);// use that config to assign a new razor service
}
public static void SendHtmlEmail(string template, EmailModel model)
{
string emailBody
= Engine.Razor.RunCompile(template, model.Type.ToString(), typeof(EmailModel), model);
var smtpClient = getStaticSmtpObject(); // an external method not included here
MailMessage message = new MailMessage();
message.From = new MailAddress(model.FromAddress);
message.To.Add(model.EmailAddress);
message.Subject = model.Subject;
message.IsBodyHtml = true;
message.Body = System.Net.WebUtility.HtmlDecode(emailBody);
smtpClient.SendAsync(message, model);
}
}
然后我可以通过传入从实际 .cshtml 模板中读取的字符串和保存电子邮件数据的模型来使用它。
string template = System.IO.File.ReadAllText(ResolveConfigurationPath("~/Views/Emails/Email.cshtml"));
SendHtmlEmail(template, model);
ResolveConfigurationPath 是我找到的另一个外部函数。
public static string ResolveConfigurationPath(string configPath)
{
if (configPath.StartsWith("~/"))
{
// +1 to Stack Overflow:
// http://stackoverflow.com/questions/4742257/how-to-use-server-mappath-when-httpcontext-current-is-nothing
// Support unit testing scenario where hosting environment is not initialized.
var hostingRoot = HostingEnvironment.IsHosted
? HostingEnvironment.MapPath("~/")
: AppDomain.CurrentDomain.BaseDirectory;
return Path.Combine(hostingRoot, configPath.Substring(2).Replace('/', '\\'));
}
return configPath;
}