.NET - Generate HTML with Razor Engine

  • 通过 Nuget 搜索并安装 RazorEngine 引擎

  • 根据模板生成 HTML

调用 RazorEngine 用于根据模板和传入的数据模型生成 HTML 文本

public static string GenerateHtml<T>(string templateText, string templateKey, T model)
{
    var config = new TemplateServiceConfiguration() {
        Debug = true,
        Language = Language.CSharp,
        EncodedStringFactory = new HtmlEncodedStringFactory()
    };
    var engine = RazorEngineService.Create(config);
    var result = engine.RunCompile(templateText, templateKey, typeof(T), model);
    return result;
}
  • 切换 AppDomain
public static int SwitchAppDomain()
{
    // RazorEngine cannot clean up from the default appdomain...

    Console.WriteLine("Switching to secound AppDomain, for RazorEngine...");
    // You only need to add strongnames when your appdomain is not a full trust environment.

    var strongNames = new StrongName[0];
    var domain = AppDomain.CreateDomain(
        "MyMainDomain",
        null,
        AppDomain.CurrentDomain.SetupInformation,
        new PermissionSet(PermissionState.Unrestricted),
        strongNames);
    var exitCode = domain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location);
    // RazorEngine will cleanup. 

    AppDomain.Unload(domain);
    return exitCode;
}

如果不调用SwitchAppDomain则在执行过程中会提示如下警告:

RazorEngine: We can't cleanup temp files if you use RazorEngine on the default Appdomain.
Create a new AppDomain and use RazorEngine from there.
Read the quickstart or https://github.com/Antaris/RazorEngine/issues/244 for details!
You can ignore this and all following 'Please clean ... manually' messages if you are using DisableTempFileLocking, which is not recommended.
Please clean 'C:\Users\Administrator\AppData\Local\Temp\RazorEngine_tj1vga2u.lda' manually!
  • 定义 Model
public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class ReportModel
{
    public IEnumerable<Student> Students { get; set; }
}
  • 定义模板
@model htmlgen.ReportModel

<html>
<body>
    <table>
        <thead>
            <tr>
                <td>Name</td>
                <td>Age</td>
            </tr>
        </thead>
        <tbody>
            @foreach (var x in Model.Students) {
            <tr>
                <td>@x.Name</td>
                <td>@x.Age</td>
            </tr>
            }
        </tbody>
    </table>
</body>
</html>
  • 主程序
namespace htmlgen
{
    class Program
    {
        static int Main(string[] args)
        {
            if (AppDomain.CurrentDomain.IsDefaultAppDomain()) {
                return SwitchAppDomain();
            }

            var model = new ReportModel() {
                Students = new Student[] {
                    new Student() { Name = "Jack", Age = 25 },
                    new Student() { Name = "Stephen", Age = 35 },
                }
            };
            var template = System.IO.File.ReadAllText("../../MyTemplate.html");
            var result = GenerateHtml(template, "templateKey", model);
            System.Console.WriteLine(result);
            return 0;
        }
    }
}

输出结果

Switching to secound AppDomain, for RazorEngine...
<html>
<body>
    <table>
        <thead>
            <tr>
                <td>Name</td>
                <td>Age</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Jack</td>
                <td>25</td>
            </tr>
            <tr>
                <td>Stephen</td>
                <td>35</td>
            </tr>
        </tbody>
    </table>
</body>
</html>