在非MVC下RazorEngine的使用

来源:互联网 发布:启示录2知乎 编辑:程序博客网 时间:2024/05/22 12:59

1、通过nuget安装RazorEngine

Razor引擎下载地址:http://github.com/Antaris/RazorEngine

2、来看代码
后台部分:

string fullPath = AppDomain.CurrentDomain.BaseDirectory+@"/Views/MyView.cshtml";//拿到cshtml文件路径string cshtml = File.ReadAllText(fullPath);//得到文件内容string cache = cache + EncrypHelper.MD5(cshtml);string myhtml = Razor.Parse(waybillCshtml, new {name="tom"}, null, cache)

再看一下页面:

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml">    <head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>     <title>测试</title>    </head>    <body>     <ul>@Model.name</ul>    </body></html>

@Model.属性 可以直接使用。
也可以指定类型Razor.Parse<T>(text, model);

看到有文章说Razor.Parse每次都会将动态编译的东西保存在内存中,参考:https://stackoverflow.com/questions/12301515/razorengine-memory-usage
所以,有下面解决办法:

  1. 加上cache
  2. 不用用3.0
  3. 用Precompiling Templates方法,参考:https://razorengine.codeplex.com/wikipage?title=Quick%20Start%20Guide&referringTitle=Documentation
原创粉丝点击