您的位置:首页 > 其它

Razor模板解密

2015-07-08 21:11 393 查看
RazorEngine将模板cshtml编译成了。一个程序集,每次编译运行,都会产生一个程序集;

可以用一个控制台程序打印出来,生成的“动态程序集“的名字(动态程序集是不能打印出磁盘中的位置的)

using RazorEngine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Razor解密
{
class Program
{
static void Main(string[] args)
{
string cshtml = File.ReadAllText(@"C:\Users\Administrator\Desktop\ceshi\Web2\Web2\Razor.cshtml");
for (int i = 0; i < 5; i++)
{
string html = Razor.Parse(cshtml);//将一个模板页转化为一个程序集
// Console.WriteLine(html);
}

//找到本程序中所有引用的程序集
Assembly[] asd = AppDomain.CurrentDomain.GetAssemblies(); //Assembly  添加using
foreach(Assembly a in asd)
{
Console.WriteLine(a.FullName+"\r\n");
}
Console.ReadKey();
}
}
}


生成的程序集如下;



产生的问题:

可以看到生成的程序集非常的多,模板每一次,有新的变量添加(页面内容的添加,就会重复编译,动态生成多个的程序集),大量程序集的影响网站的打开速度的性能

解决办法:给模板页取个别名”缓存名字“

using RazorEngine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Razor解密
{
class Program
{
static void Main(string[] args)
{
/*
string cshtml = File.ReadAllText(@"C:\Users\Administrator\Desktop\ceshi\Web2\Web2\Razor.cshtml");
*/

/*
for (int i = 0; i < 5; i++)
{

//给要解析模板文件cshtml一个别名字"缓存名",c1
//这次一旦编成功后,下次如果是再次编译这个相同的模板文件cshtml的话,就让RazorEngine引擎来转换c1好了
string html = Razor.Parse(cshtml, null, "c1");
//为了好理解,可以给这个cshtml相同的模板文件再起个别的缓存名字"c2"
//
}
*/

/*
string html = Razor.Parse(cshtml, null, "c1");
Razor.Parse(cshtml, null, "c2");

*/
//1.取得文件的路径
string fullPath=File.ReadAllText(@"C:\Users\Administrator\Desktop\ceshi\Web2\Web2\Razor.cshtml");

for (int i = 0; i < 10; i++)
{
//2.读出模板中的内容
string cshtml = File.ReadAllText(fullPath);
//取文件的全路径+文件修改的时间做cacheName不一样(每一次文件的编译的时候用的都是同一个缓存的名字)
//修改时间保证相同文件做了内容修改之后的cacheName不一样(也可以用文件内容的MD5值,)
string cacheName = fullPath + File.GetLastWriteTime(fullPath);
string html = Razor.Parse(cshtml, null, cacheName);
Console.WriteLine(html);
}

//找到本程序中所有引用的程序集
Assembly[] asd = AppDomain.CurrentDomain.GetAssemblies(); //Assembly  添加using
foreach(Assembly a in asd)
{
Console.WriteLine(a.FullName+"\r\n");
}
Console.ReadKey();
}
}
}


取了一个别名字后动态程序集生成的效果

发现只有一个了



给同一个模板页取两个不同的别名字后效果



给同一个模板页取加上时间的别名字后效果



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: