目录

  • Brief
  • Authors
  • Official Website
  • RazorEngine 的原理 - 官方解释
  • 安装记录
  • Supported Syntax (默认实现支持的语法)
  • 测试记录 - can't cleanup temp files
  • 测试记录 - Quick Start
  • 测试记录 - Configuration
  • 测试记录 - 对比 3 种 Type 的 model 的语法
  • 测试记录 - 扩展模板语法
  • 测试记录 - Layout
  • 测试记录 - Partial (@Include())
  • Encoding Values - @Raw()
  • RazorEngine.Razor 已废弃,请改用 Engine.Razor
  • 缓存
  • 作者说: 无法稍毁缓存
  • 某网文代码
  • 安全 - 只可能内部使用、不能让用户定义模板
  • Resource - Hello World
  • Resource - Advanced
  • base or advanced

Brief

Open source templating engine based on Microsoft's Razor parsing engine.

Authors

  • Matthew Abbott
  • Ben Dornis
  • Matthias Dittrich

Official Website

GitHub

CodePlex - obsolete

NuGet

Install-Package RazorEngineInstall-Package RazorEngine -Version 3.6.4https://www.nuget.org/packages/RazorEngine/ - latest: RazorEngine 3.6.4, Friday, March 27 2015

Stack Overflow

RazorEngine 的原理 - 官方解释

There is often a confusion about where Razor sits in this set of technologies. Essentially Razor is the parsing framework that does the work to take your text template and convert it into a compilable class. In terms of MVC and WebPages, they both utilise this parsing engine to convert text templates (view/page files) into executable classes (views/pages). Often we are asked questions such as "Where is @Html, @Url", etc. These are not features provided by Razor itself, but implementation details of the MVC and WebPages frameworks.

RazorEngine is another consumer framework of the Razor parser. We wrap up the instantiation of the Razor parser and provide a common framework for using runtime template processing.

-- Razor vs. MVC vs. WebPages vs. RazorEngine

安装记录

Installed into Net451Console via NuGet at 2016-07-31:


总结: 共安装了两个 DLL: System.Web.Razor.dllRazorEngine.dll

1. -------正在安装...RazorEngine3.9.0-------
2. 正在尝试解析依赖项“Microsoft.AspNet.Razor(≥3.0.0)”。
3. 正在安装“Microsoft.AspNet.Razor3.0.0”。
4. 已将文件“System.Web.Razor.dll”添加到文件夹“Microsoft.AspNet.Razor.3.0.0\lib\net45”。
5. 已将文件“System.Web.Razor.xml”添加到文件夹“Microsoft.AspNet.Razor.3.0.0\lib\net45”。
6. 已将文件“Microsoft.AspNet.Razor.3.0.0.nuspec”添加到文件夹“Microsoft.AspNet.Razor.3.0.0”。
7. 已将文件“Microsoft.AspNet.Razor.3.0.0.nupkg”添加到文件夹“Microsoft.AspNet.Razor.3.0.0”。
8. 已成功安装“Microsoft.AspNet.Razor3.0.0”。
9. 正在安装“RazorEngine3.9.0”。
10. 已将文件“RazorEngine.dll”添加到文件夹“RazorEngine.3.9.0\lib\net40”。
11. 已将文件“RazorEngine.xml”添加到文件夹“RazorEngine.3.9.0\lib\net40”。
12. 已将文件“RazorEngine.dll”添加到文件夹“RazorEngine.3.9.0\lib\net45”。
13. 已将文件“RazorEngine.xml”添加到文件夹“RazorEngine.3.9.0\lib\net45”。
14. 已将文件“LICENSE.md”添加到文件夹“RazorEngine.3.9.0”。
15. 已将文件“RazorEngine.3.9.0.nuspec”添加到文件夹“RazorEngine.3.9.0”。
16. 已将文件“RazorEngine.3.9.0.nupkg”添加到文件夹“RazorEngine.3.9.0”。
17. 已成功安装“RazorEngine3.9.0”。
18. 正在将“Microsoft.AspNet.Razor3.0.0”添加到Console。
19. 已将引用“System.Web.Razor”添加到项目“Console”
20. 已添加文件“packages.config”。
21. 已将文件“packages.config”添加到项目“Console”
22. 已成功将“Microsoft.AspNet.Razor3.0.0”添加到Console。
23. 正在将“RazorEngine3.9.0”添加到Console。
24. 已将引用“RazorEngine”添加到项目“Console”
25. 已添加文件“packages.config”。
26. 已成功将“RazorEngine3.9.0”添加到Console。
27. ==============================

Supported Syntax (默认实现支持的语法)

You can access several things when you use the default TemplateBase<> implementation:
@using Custom.Namespace (see also the quick intro and assembly resolvers for custom references)
@model ModelType@inherits HtmlSupportTemplateBase<ModelType> (see below)
* Set a layout (and @RenderBody() within the layout template): @{ Layout = "layout.cshtml"; }@Include("templateName", model = null, modelType = null) to include another template.
* Accessing the ViewBag: <h1>@ViewBag.Title</h1>* Sections (@DefineSection@RenderSection and @IsSectionDefined)

-- http://antaris.github.io/RazorEngine/TemplateBasics.html#Supported-syntax

测试记录 - can't cleanup temp files

2015-10-19 Tony 在 .NET4.51 Console Application 中单步执行以下代码时弹出命令行窗口显示以下信息:

代码:

1. usingRazorEngine;
2. usingRazorEngine.Templating;
3. 
4. namespaceNet451ConsoleApplication
5. {
6. classProgram
7. {
8. staticvoidMain(string[])
9. {
10. // using RazorEngine.Templating; // Dont forget to include this.
11. stringtemplate="Hello @Model.Name, welcome to RazorEngine!";
12. var=Engine.Razor.RunCompile(template,"templateKey",null,new{Name="World"});
13. }
14. }
15. }


每次单步执行 RazorEngine.Engine.Razor.RunCompile() 后,都会生成 1 个目录及该目录中的 6 个文件,该目录及其中的全部文件的名称都是随机的,例如:

1. RazorEngine:We't cleanup temp files if you use RazorEngine on the default Appdomain.
2. Create a new AppDomain and use RazorEngine from there.
3. Read the quickstart or https://github.com/Antaris/RazorEngine/issues/244 for details!
4. You can ignore this and all following 'Please...' messages if you are using DisableTempFileLocking, which is not recommended.
5. Please clean 'C:\Users\User0\AppData\Local\Temp\RazorEngine_********.***' manually!
1. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\CompiledRazorTemplates.Dynamic.RazorEngine_290440367cc04e8c9d06a99a7a805d08.dll"
2. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\filbbops.0.cs"
3. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\filbbops.cmdline"
4. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\filbbops.err"
5. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\filbbops.out"
6. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\filbbops.tmp"

单步执行完毕后 (Tony 理解为应用程序域已终止并释放),其它 5 个文件已自动移除,但 .dll 文件及该目录会残留。以下为 4 次单步执行后的残留:

1. "C:\Users\User0\AppData\Local\Temp\RazorEngine_bmze52rx.ovb\CompiledRazorTemplates.Dynamic.RazorEngine_a291215db8fd497cae3e4a2bfcabe7b2.dll"
2. "C:\Users\User0\AppData\Local\Temp\RazorEngine_tkidehx4.qay\CompiledRazorTemplates.Dynamic.RazorEngine_bd299256d8b94f64ba943c5a09014ed6.dll"
3. "C:\Users\User0\AppData\Local\Temp\RazorEngine_a1anyws2.vvo\CompiledRazorTemplates.Dynamic.RazorEngine_f890b330f6104de19631e25ea528a6e8.dll"
4. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\CompiledRazorTemplates.Dynamic.RazorEngine_290440367cc04e8c9d06a99a7a805d08.dll"

官网提供了上述问题的解决方案,2017-03-15 编写以下代码对该方案进行了测试,结论: 该方案在控制台程序中有效:



1. //Program.cs
2. 
3. usingRazorEngine;
4. usingRazorEngine.Templating;
5. 
6. namespaceNet451Console
7. {
8. classProgram
9. {
10. //static void Main(string[] args)
11. staticintMain(string[])
12. {
13. bool=NewDomain.Switch();
14. if(isDefaultAppDomain){
15. return0;
16. }
17. 
18. #region test code:
19. stringtemplate="Hello @Model.Name, welcome to RazorEngine!";
20. var=Engine.Razor.RunCompile(template,"templateKey",null,new{Name="World"});
21. //执行上一行后创建了 "C:\Users\User0\AppData\Local\Temp\RazorEngine_tbr5ujmj.fju" 目录及其中的 6 个文件。
22. var==="Hello World, welcome to RazorEngine!";
23. #endregion test code.
24. 
25. return123;
26. }
27. //退出 Main() 后 "C:\Users\User0\AppData\Local\Temp\RazorEngine_tbr5ujmj.fju" 目录被删除。
28. }
29. }
1. //NewDomain.cs
2. 
3. usingSystem;
4. usingSystem.Reflection;
5. usingSystem.Security;
6. usingSystem.Security.Permissions;
7. usingSystem.Security.Policy;
8. 
9. namespaceNet451Console
10. {
11. classNewDomain
12. {
13. /// <summary>
14. /// 如果 应用程序域 非 进程的默认应用程序域,则 不作任何处理、直接返回 false;
15. /// 如果 应用程序域 是 进程的默认应用程序域,则 创建新的应用程序域、并在该域中执行当前程序集、接着卸载该域、并返回 true。
16. /// </summary>
17. publicstaticboolSwitch()
18. {
19. bool=AppDomain.CurrentDomain.IsDefaultAppDomain();
20. if(!isDefaultAppDomain){
21. returnfalse;
22. }
23. 
24. // RazorEngine cannot clean up from the default appdomain...
25. Console.WriteLine("Switching to second AppDomain, for RazorEngine...");
26. 
27. //2017-03-15 已测试证明以下两行代码无用:
28. //AppDomainSetup adSetup = new AppDomainSetup();
29. //adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
30. //测试记录: 至此 adSetup.ApplicationBase 的值为 "D:\Test\Net451Console\branches\RazorEngine\Net451Console\bin\Debug\"。
31. 
32. // You only need to add strongnames when your appdomain is not a full trust environment.
33. AppDomain=AppDomain.CreateDomain(
34. "MyMainDomain",
35. null,
36. AppDomain.CurrentDomain.SetupInformation,
37. newPermissionSet(PermissionState.Unrestricted),
38. newStrongName[0]
39. );
40. string=Assembly.GetExecutingAssembly().Location;
41. //测试记录: 至此 location 的值为 "D:\Test\Net451Console\branches\RazorEngine\Net451Console\bin\Debug\Net451Console.exe"。
42. int=.ExecuteAssembly(location);
43. //执行上一行的 domain.ExecuteAssembly() 导致重新执行 Main(),届时 isDefaultAppDomain 为 false,将跳过本方法主体转而执行 Mian() 中的剩余代码,Main() 的返回值将成为上一行的返回值并赋给 exitCode,接着执行下 2 行代码,最后退出本方法。
44. // Note that you need to Unload the domain to trigger cleanup.
45. // RazorEngine will cleanup.
46. AppDomain.Unload(domain);
47. //执行上一行后 "C:\Users\User0\AppData\Local\Temp\RazorEngine_tbr5ujmj.fju" 目录中的 6 个文件仅剩下 1 个 .dll 文件。
48. returntrue;
49. }
50. }
51. }

测试记录 - 以上方案仅在控制台程序中有效、在 ASP.NET MVC 中无效

  1. 在 ASP.NET MVC 中 AppDomain.CurrentDomain.IsDefaultAppDomain() 总是返回 false
  2. 执行 Assembly.GetExecutingAssembly().Location 返回 C:\Users\User0\AppData\Local\Temp\Temporary ASP.NET Files\root\b54c3416\14425600\assembly\dl3\57a31749\d172b5e9_d29fd201\Net451MvcNoAuth.dll,接着执行下一行 domain.ExecuteAssembly(location) 报错 异常详细信息: System.MissingMethodException: 未在程序集“Net451MvcNoAuth, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中找到入口点。

测试记录 - Quick Start

以下测试代码整理自 http://antaris.github.io/RazorEngine/index.html#Quickstart:


测试记录 - Configuration

1. usingRazorEngine;
2. usingRazorEngine.Templating;
3. 
4. namespaceNet451Console
5. {
6. classProgram
7. {
8. //static void Main(string[] args)
9. staticintMain(string[])
10. {
11. bool=NewDomain.Switch();
12. if(isDefaultAppDomain){
13. return0;
14. }
15. 
16. #region test code:
17. //All you need to do is use the static Engine class (the Engine.Razor instance) in the 'RazorEngine' namespace:
18. stringtemplate="Hello @Model.Name, welcome to RazorEngine!";
19. string="templateKey";
20. var=Engine.Razor.RunCompile(template,,null,new{Name="World"});
21. 
22. //The "templateKey" must be unique and after running the above example you can re-run the cached template with this key.
23. var=Engine.Razor.Run(key,null,new{Name="Max"});
24. 
25. //The null parameter is the modelType and null in this case means we use dynamic as the type of the model. You can use a static model as well by providing a type object.
26. var=Engine.Razor.RunCompile(key,typeof(Person),newPerson{Name="Max"});
27. //Note that we now re-compile the model with a different type. When you do not run the same template a lot of times (like several 1000 times), compiling uses the most time. So the benefit you get from a static type will most likely not compensate the additional compile time. Therefore you should either stick to one type for a template (best of both worlds) or just use (the slower) dynamic (null). You can specify the modelType of a template with the @model directive. When you do this the modelType parameter is ignored, but you should use the same type instance (or null) on every call to prevent unnecessary re-compilations because of type mismatches in the caching layer.
28. #endregion test code.
29. 
30. return123;
31. }
32. }
33. publicclassPerson
34. {
35. publicstringName{get;set;}
36. }
37. }

以下测试代码整理自 http://antaris.github.io/RazorEngine/index.html#Configuration:


上述代码中的 d:/mytemplate.cshtml 的测试记录:

1. usingRazorEngine;
2. usingRazorEngine.Configuration;
3. usingRazorEngine.Templating;
4. usingRazorEngine.Text;
5. 
6. namespaceNet451Console
7. {
8. classProgram
9. {
10. //static void Main(string[] args)
11. staticintMain(string[])
12. {
13. bool=NewDomain.Switch();
14. if(isDefaultAppDomain){
15. return0;
16. }
17. 
18. #region test code:
19. //You can configure RazorEngine with the TemplateServiceConfiguration class.
20. var=newTemplateServiceConfiguration();
21. 
22. // ... configure your instance
23. 
24. //General Configuration
25. //By default RazorEngine is configured to encode using Html. This supports the majority of users but with some configuration changes you can also set it to encode using Raw format which is better suited for templates that generate things like javascript, php, C# and others.
26. .Language=Language.CSharp;// C# as template language.
27. .EncodedStringFactory=newRawStringFactory();// Raw string encoding.
28. //config.EncodedStringFactory = new HtmlEncodedStringFactory(); // Html encoding.
29. 
30. //One thing you might want to enable is the debugging feature:
31. .Debug=true;
32. 
33. IRazorEngineService=RazorEngineService.Create(config);
34. 
35. //If you want to use the static Engine class with this new configuration:
36. Engine.Razor=;
37. 
38. //When Debug is true you can straight up debug into the generated code. RazorEngine also supports debugging directly into the template files (normally .cshtml files). As as you might see in the above code there is no file to debug into. To provide RazorEngine with the necessary information you need to tell where the file can be found:
39. stringtemplate="Hello @Model.Name, welcome to RazorEngine!";
40. string="d:/mytemplate.cshtml";
41. // Provide a non-null file to improve debugging
42. var=newLoadedTemplateSource(template,);
43. var=Engine.Razor.RunCompile(loadedTemplateSource,"templateKey",null,new{Name="World"});
44. //This time when debugging the template you will jump right into the template file.
45. #endregion test code.
46. 
47. return123;
48. }
49. }
50. }
  • 该文件中的断点有效。
  • 该文件的内容与 template 的值无关。
  • 该文件的内容可为任意字符 (包括空文件)。
  • 该文件不能放在 Windows10 的 C 分区,否则会因为访问权限而报错。

测试记录 - 对比 3 种 Type 的 model 的语法

以下测试代码整理自 http://antaris.github.io/RazorEngine/TemplateBasics.html:


测试记录 - 扩展模板语法

1. usingRazorEngine;
2. usingRazorEngine.Templating;
3. usingSystem.Dynamic;
4. 
5. namespaceNet451Console
6. {
7. classProgram
8. {
9. //static void Main(string[] args)
10. staticintMain(string[])
11. {
12. bool=NewDomain.Switch();
13. if(isDefaultAppDomain){
14. return0;
15. }
16. 
17. #region test code:
18. stringtemplate="<div>Hello @Model.Name</div>";
19. 
20. var=newPerson{Name="Matt"};//statically type
21. var=new{Name="Matt"};//anonymous type
22. dynamic=newExpandoObject();//dynamic type
23. .Name="Matt";//dynamic type
24. 
25. string=Engine.Razor.RunCompile(template,"key0",typeof(Person),);//statically type
26. string=Engine.Razor.RunCompile(template,"key1",null,);//anonymous type
27. string=Engine.Razor.RunCompile(template,"key2",null,(object)model2);//dynamic type
28. //执行至此 result0-2 均为 "<div>Hello Matt</div>"。
29. #endregion test code.
30. 
31. return123;
32. }
33. }
34. 
35. publicclassPerson
36. {
37. publicstringName{get;set;}
38. }
39. }

以下测试代码整理自 http://antaris.github.io/RazorEngine/TemplateBasics.html#Extending-the-template-Syntax:


测试记录 - Layout

1. usingRazorEngine.Configuration;
2. usingRazorEngine.Templating;
3. usingRazorEngine.Text;
4. usingSystem;
5. 
6. namespaceNet451Console
7. {
8. classProgram
9. {
10. //static void Main(string[] args)
11. staticintMain(string[])
12. {
13. bool=NewDomain.Switch();
14. if(isDefaultAppDomain){
15. return0;
16. }
17. 
18. #region test code:
19. var=newTemplateServiceConfiguration();
20. // You can use the @inherits directive instead (this is the fallback if no @inherits is found).
21. .BaseTemplateType=typeof(HtmlSupportTemplateBase<>);
22. using(var=RazorEngineService.Create(config)){
23. string="@Model.Data";
24. string="@Html.Raw(Model.Data)";
25. string="My raw double quotes appears here \"hello!\"";
26. var=new{Data=};
27. 
28. string=.RunCompile(template0,"htmlRawTemplate0",null,);
29. string=.RunCompile(template1,"htmlRawTemplate1",null,);
30. 
31. if(result0 =="My raw double quotes appears here "hello!""){
32. Console.WriteLine("* 默认行为: 引号被 HTML 实体编码。");
33. }
34. if(result1 ==){
35. Console.WriteLine("* @Html.Raw() 原样输出。");
36. }
37. }
38. #endregion test code.
39. 
40. return123;
41. }
42. }
43. 
44. publicclassMyHtmlHelper
45. {
46. publicIEncodedStringRaw(string)
47. {
48. returnnewRawString(rawString);
49. }
50. }
51. 
52. publicabstractclassHtmlSupportTemplateBase<T>:TemplateBase<T>
53. {
54. //public MyClassImplementingTemplateBase()
55. publicHtmlSupportTemplateBase()
56. {
57. Html=newMyHtmlHelper();
58. }
59. publicMyHtmlHelperHtml{get;set;}
60. }
61. }

以下测试代码整理自 http://antaris.github.io/RazorEngine/LayoutAndPartial.html#Layout-template:


测试记录 - Partial (@Include())

1. usingRazorEngine;
2. usingRazorEngine.Templating;
3. 
4. namespaceNet451Console
5. {
6. classProgram
7. {
8. //static void Main(string[] args)
9. staticintMain(string[])
10. {
11. bool=NewDomain.Switch();
12. if(isDefaultAppDomain){
13. return0;
14. }
15. 
16. #region test code:
17. IRazorEngineService=Engine.Razor;
18. .AddTemplate("Layout0",@"<html>@RenderBody()</html>");
19. .AddTemplate("Layout1",@"<body>@RenderBody()</body>@{ Layout = ""Layout0""; }");
20. .AddTemplate("Layout2",@"<div> @RenderBody()</div> @{ Layout = ""Layout1""; }");
21. .AddTemplate("templet",@"<h1>  content in h1</h1>  @{ Layout = ""Layout2""; }");
22. .Compile("templet");
23. string=.Run("templet");
24. bool==="<html><body><div> <h1>  content in h1</h1>  </div> </body></html>";
25. #endregion test code.
26. 
27. return123;
28. }
29. }
30. }

以下测试代码整理自 http://antaris.github.io/RazorEngine/LayoutAndPartial.html#Partial-templates:


测试发现很多参数都可省略:

1. usingRazorEngine;
2. usingRazorEngine.Templating;
3. 
4. namespaceNet451Console
5. {
6. classProgram
7. {
8. //static void Main(string[] args)
9. staticintMain(string[])
10. {
11. bool=NewDomain.Switch();
12. if(isDefaultAppDomain){
13. return0;
14. }
15. 
16. #region test code:
17. var=Engine.Razor;
18. .AddTemplate("part",@"my template");
19. // If you leave the second and third parameters out the current model will be used.
20. // If you leave the third we assume the template can be used for multiple types and use "dynamic".
21. // If the second parameter is null (which is default) the third parameter is ignored.
22. // To workaround in the case you want to specify type "dynamic" without specifying a model use Include("p", new object(), null)
23. .AddTemplate("template",@"<h1>@Include(""part"", @Model.SubModel, typeof(Net451Console.SubModel))</h1>");
24. .Compile("template",typeof(MyModel));
25. .Compile("part",typeof(SubModel));
26. var=.Run(
27. "template",
28. typeof(MyModel),
29. newMyModel{
30. ModelProperty="model",
31. SubModel=newSubModel{SubModelProperty="submodel"}
32. }
33. );
34. bool==="<h1>my template</h1>";
35. #endregion test code.
36. 
37. return123;
38. }
39. }
40. 
41. publicclassSubModel
42. {
43. publicstringSubModelProperty{get;set;}
44. }
45. 
46. publicclassMyModel
47. {
48. publicstringModelProperty{get;set;}
49. publicSubModelSubModel{get;set;}
50. }
51. }


Encoding Values - @Raw()

1. usingRazorEngine;
2. usingRazorEngine.Templating;
3. 
4. namespaceNet451Console
5. {
6. classProgram
7. {
8. //static void Main(string[] args)
9. staticintMain(string[])
10. {
11. bool=NewDomain.Switch();
12. if(isDefaultAppDomain){
13. return0;
14. }
15. 
16. #region test code:
17. var=Engine.Razor;
18. .AddTemplate("part",@"Text in the part.");
19. .AddTemplate("template",@"<h1>@Include(""part"")</h1>");
20. .Compile("template");
21. .Compile("part");
22. var=.Run("template");
23. bool==="<h1>Text in the part.</h1>";
24. #endregion test code.
25. 
26. return123;
27. }
28. }
29. }

以下测试代码整理自 http://antaris.github.io/RazorEngine/Encoding.html:


测试记录 - 不支持 @Html.Raw()

1. usingRazorEngine;
2. usingRazorEngine.Templating;
3. 
4. namespaceNet451Console
5. {
6. classProgram
7. {
8. //static void Main(string[] args)
9. staticintMain(string[])
10. {
11. bool=NewDomain.Switch();
12. if(isDefaultAppDomain){
13. return0;
14. }
15. 
16. #region test code:
17. //By default RazorEngine is configured to encode as Html. This sometimes this presents problems were certain characters are encoded as Html but what you want is to output them as-is. To output something in raw format use the @Raw() built-in method as shown in the following example:
18. string="@Model.Data";
19. string="@Raw(Model.Data)";
20. var=new{Data="My raw double quotes appears here \"hello!\""};
21. string=Engine.Razor.RunCompile(template0,"templateKey0",null,);
22. string=Engine.Razor.RunCompile(template1,"templateKey1",null,);
23. bool===@"My raw double quotes appears here "hello!"";
24. bool===@"My raw double quotes appears here ""hello!""";
25. #endregion test code.
26. 
27. return123;
28. }
29. }
30. }

执行 string test = Engine.Razor.RunCompile(@"@Html.Raw(""asdf"")", "key", null, string.Empty); 时抛出异常 "当前上下文中不存在名称“Html”"。

RazorEngine.Razor 已废弃,请改用 Engine.Razor


缓存

1. #region 程序集 RazorEngine.dll, v3.9.0.0
2. // D:\Test\Net451Console\branches\RazorEngine\packages\RazorEngine.3.9.0\lib\net45\RazorEngine.dll
3. #endregion
4. 
5. namespaceRazorEngine
6. {
7. [Obsolete("Please use the Engine.Razor instance instead.")]
8. publicstaticclassRazor{
9. publicstaticvoidCompile(string,string);
10. ...
11. publicstaticITemplateCreateTemplate(string);
12. ...
13. publicstaticITemplateGetTemplate(string,string);
14. ...
15. publicstaticstringParse(string);
16. ...
17. publicstaticITemplateResolve(string);
18. ...
19. publicstaticstringRun(string);
20. ...
21. publicstaticvoidSetTemplateService(ITemplateService);
22. }
23. }
  1. How are templates in RazorEngine cached?
  2. Antaris RazorEngine How to Recompile a template using the same Key?
  3. RazorEngine Memory Usage
  4. RazorEngine IsolatedTemplateService is not preventing growth of number of loaded assemblies
  5. Use external cache provider for RazorEngine
  6. Memcached Caching Provider and Serialization Issue #278

作者说: 无法稍毁缓存

When you change and recompile templates you have a memory leak, because you cannot unload loaded assemblies (which RazorEngine compiles and loads for you in the background).

The only way to really free the memory is to reload the AppDomain or restart the process.

-- http://stackoverflow.com/questions/14369614/razorengine-un-cache-compiled-templates

某网文代码

ASP.NET MVC 解析模板生成静态页一 (RazorEngine)》 全文共两部分: 1. 基本的单数据模型模板解析; 2. 面向接口的多数据模型模板解析。该网文仅涉及到 RazorEngine 最基础的 API,未展示 Hello World 之外的功能。以下为第一部分的原始代码 (未改动、仅格式化)。第二部分核心代码与第一部分完全相同,仅增加了 TemplateView 模型解析类中间件、Repository、泛型、面向接口、Spring 依赖注入、反射赋值,所有这些增加的部分都是面向对象与设计模式的半桶水套路,无作用无意义徒增坏味道,跳过。



1. publicclassArticles
2. {
3. publicintId{get;set;}
4. publicstringTitle{get;set;}
5. publicstringContent{get;set;}
6. publicstringAuthor{get;set;}
7. publicDateTimeCreateDate{get;set;}
8. }


1. <htmlxmlns="http://www.w3.org/1999/xhtml">
2. <head>
3. <metahttp-equiv="Content-Type"content="text/html; charset=utf-8"/>
4. <title>@Model.Title</title>
5. </head>
6. <body>
7. <h1>@Model.Title</h1>
8. <p>作者:@Model.Author - 发布时间:@Model.CreateDate</p>
9. <p>@Raw(Model.Content)</p>
10. </body>
11. </html>


1. /// <summary>
2. /// 获取页面的Html代码
3. /// </summary>
4. /// <param name="url">模板页面路径</param>
5. /// <param name="encoding">页面编码</param>
6. publicstringGetHtml(string,System.Text.Encoding)
7. {
8. byte[]=newWebClient().DownloadData(url);
9. if(encoding !=null){
10. return.GetString(buf);
11. }
12. string=System.Text.Encoding.UTF8.GetString(buf);
13. =GetEncoding(html);
14. if(encoding ==null||==System.Text.Encoding.UTF8){
15. return;
16. }
17. return.GetString(buf);
18. }
19. 
20. /// <summary>
21. /// 获取页面的编码
22. /// </summary>
23. /// <param name="html">Html源码</param>
24. publicSystem.Text.EncodingGetEncoding(string)
25. {
26. string=@"(?i)/bcharset=(?<charset>[-a-zA-Z_0-9]+)";
27. string=Regex.Match(html,).Groups["charset"].Value;
28. try{
29. returnSystem.Text.Encoding.GetEncoding(charset);
30. }
31. catch(ArgumentException){
32. returnnull;
33. }
34. }


1. /// <summary>
2. /// 创建静态文件
3. /// </summary>
4. /// <param name="result">Html代码</param>
5. /// <param name="createpath">生成路径</param>
6. publicboolCreateFileHtmlByTemp(string,string)
7. {
8. if(!string.IsNullOrEmpty(result)){
9. if(string.IsNullOrEmpty(createpath)){
10. ="/default.html";
11. }
12. string=.Substring(createpath.LastIndexOf(@"/"));
13. =.Substring(0,.LastIndexOf(@"/"));
14. if(!Directory.Exists(createpath)){
15. Directory.CreateDirectory(createpath);
16. }
17. =+;
18. try{
19. FileStream=newFileStream(createpath,FileMode.Create);
20. StreamWriter=newStreamWriter(fs2,newSystem.Text.UTF8Encoding(false));//去除UTF-8 BOM
21. .Write(result);
22. .Close();
23. .Close();
24. .Dispose();
25. returntrue;
26. }
27. catch{returnfalse;}
28. }
29. returnfalse;
30. }

安全 - 只可能内部使用、不能让用户定义模板

1. /// <summary>
2. /// 解析模板生成静态页
3. /// </summary>
4. /// <param name="temppath">模板地址</param>
5. /// <param name="path">静态页地址</param>
6. /// <param name="t">数据模型</param>
7. publicboolCreateStaticPage(string,string,Articles)
8. {
9. try{
10. //获取模板Html
11. stringTemplateContent=GetHtml(temppath,System.Text.Encoding.UTF8);
12. //解析模板生成静态页Html代码
13. string=Razor.Parse(TemplateContent,);
14. //创建静态文件
15. returnCreateFileHtmlByTemp(result,);
16. }
17. catch(Exception){
18. throw;
19. }
20. }
  1. How dangerous is it to let users specify RazorEngine templates?
  2. RazorEngine for user templates - Security?
  3. ASP.NET Razor templates editable by users - remove @ for security reasons

Resource - Hello World

  1. 利用 RazorEngine 打造简单的泛用代码生成器 - 基于 ExpandoObject
  2. 利用 RazorEngine 更加直观的格式化字符串 - Note: 反射取值的 Regex.Replace() 有实用价值

Resource - Advanced

  1. 第四篇 基于 .NET 搭建热插拔式 Web 框架 (RazorEngine 实现)
  2. 用 Razor 語法寫範本 - RazorEngine 組件介紹
  3. 让 Windows2003 Server NET4.0 Frameworks 可以上使用 RazorEngine 程序集
  4. C# 模板引擎 RazorEngine 3.7 的简单使用
  5. RazorEngine 在非 MVC 下的使用,以及使用自定义模板
  6. .NET MVC Razor 也可以这样玩
  7. 在 ASP.NET WebAPI 中使用 Razor
  8. DIY RazorEngine 的程序集生成方式
  9. 抛弃 NVelocity,来玩玩 Razor - 文件嵌套、@Include()
  10. Razor Engine,实现代码生成器的又一件利器
  11. Razor 模板引擎使用 - 缓存源码?
  12. C# & SQlite 代码生成器 - 非 HTML 模板示例
  13. Razor 模板引擎 - 缓存测试 & 封装
  14. 使用 Razor 模板构建应用注意的细节

base or advanced

  1. 用 Razor 語法寫範本 - RazorEngine 組件介紹
  2. 用 Razor 語法寫範本 - RazorEngine 組件介紹
  3. 让 Windows2003 Server NET4.0 Frameworks 可以上使用 RazorEngine 程序集
  4. RazorEngine - @Html.LabelFor OK, @Html.EditorFor "not implemented exception" on Execute()
  5. Dynamic CSS using Razor Engine
  6. Razor Templating Engine
  7. 代码生成就用 Razor 模板
  8. C# 模板引擎 RazorEngine 3.7 的扩展 — 引入外部文件
  9. C# 模板引擎 RazorEngine 3.7 的扩展 — 引用布局页
  10. 在非网页程序里使用 Razor 模板引擎
  11. ASP.NET MVC 解析模板生成静态页一 (RazorEngine) - 详见本文 "某网文代码" 小节
  12. DIY RazorEngine 的程序集生成方式