ASP.NET MVC生成静态页面的方法
本文主要讲述了在asp.NETmvc中,页面静态化的方法。对于网站来说,生成纯html静态页面除了有利于seo外,还可以减轻网站的负载能力和提高网站性能。
1.先付上封装好生成静态页的原代码:
publicclassCommon
{
#region获取模板页的Html代码
///
///获取页面的Html代码
///
///模板页面路径
///页面编码
///
publicstaticstringGetHtml(stringurl,System.Text.Encodingencoding)
{
byte[]buf=newWebClient().DownloadData(url);
if(encoding!=null)
{
returnencoding.GetString(buf);
}
stringhtml=System.Text.Encoding.UTF8.GetString(buf);
encoding=GetEncoding(html);
if(encoding==null||encoding==System.Text.Encoding.UTF8)
{
returnhtml;
}
returnencoding.GetString(buf);
}
///
///获取页面的编码
///
///Html源码
///
publicstaticSystem.Text.EncodingGetEncoding(stringhtml)
{
stringpattern=@"(?i)\bcharset=(?[-a-zA-Z_0-9]+)";
stringcharset=Regex.Match(html,pattern).Groups["charset"].Value;
try
{
returnSystem.Text.Encoding.GetEncoding(charset);
}
catch(ArgumentException)
{
returnnull;
}
}
#endregion
#region用于生成Html静态页
///
///创建静态文件
///
///Html代码
///生成路径
///
publicstaticboolCreateFileHtmlByTemp(stringresult,stringcreatepath)
{
if(!string.IsNullOrEmpty(result))
{
if(string.IsNullOrEmpty(createpath))
{
createpath="/default.html";
}
stringfilepath=createpath.Substring(createpath.LastIndexOf(@"\"));
createpath=createpath.Substring(0,createpath.LastIndexOf(@"\"));
if(!Directory.Exists(createpath))
{
Directory.CreateDirectory(createpath);
}
createpath=createpath+filepath;
try
{
FileStreamfs2=newFileStream(createpath,FileMode.Create);
StreamWritersw=newStreamWriter(fs2,newSystem.Text.UTF8Encoding(false));//去除UTF-8BOM
sw.Write(result);
sw.Close();
fs2.Close();
fs2.Dispose();
returntrue;
}
catch(Exceptionex)
{
throwex;
}
}
returnfalse;
}
#endregion
#region调用静态模板,并且传递数据模型实体类创建Html静态页
///
///解析模板生成静态页
///
///模板地址
///静态页地址
///数据模型
///
publicstaticboolCreateStaticPage(stringtemppath,stringpath,Tt)
{
try
{
//获取模板Html
stringTemplateContent=GetHtml(temppath,System.Text.Encoding.UTF8);
//初始化结果
stringresult=string.Empty;
//解析模板生成静态页Html代码
result=Razor.Parse(TemplateContent,t);
//创建静态文件
returnCreateFileHtmlByTemp(result,path);
}
catch(Exceptione)
{
throwe;
}
}
#endregion
}
2.调用方法(创建一个多线程去执行,效果会更好):
//实例化调用方法 Tasktk=newTask(CreateStaticHtml); tk.Start(); //静态调用方法 Task.Factory.StartNew(()=>CreateStaticHtml());
3.封装好的静态方法:
//////创建静态页面 /// publicvoidCreateStaticHtml() { using(BangLiEntitiesbangLi=newBangLiEntities()) { View_Homeview_Home=newView_Home(); view_Home.CommandAdExtendList=Dal.CommandAdDal.Instance(bangLi).GetInit().ToList(); view_Home.NewsList=bangLi.News.OrderByDescending(u=>u.AddDateTime).Take(5).ToList(); view_Home.NewsExtendList=Dal.NewsDal.Instance(bangLi).GetInit().OrderByDescending(u=>u.AddDateTime).Take(5).ToList(); view_Home.News=Dal.NewsDal.Instance(bangLi).GetInit().Where(u=>u.Id==3).SingleOrDefault(); stringTemplateContent=Common.GetHtml(Server.MapPath("/Views/SourceHtml/Home/Index.cshtml"),System.Text.Encoding.UTF8); //初始化结果 stringresult=string.Empty; //解析模板生成静态页Html代码 result=Razor.Parse(TemplateContent,view_Home); //创建静态文件 Common.CreateFileHtmlByTemp(result,Server.MapPath("/Resource/Manage/Html/Home/Index.html")); } }
4.如首页执行时,可以在执行Action前去执行一个过滤器:
publicclassMyFirstHomeAttribute:ActionFilterAttribute
{
publicoverridevoidOnActionExecuting(ActionExecutingContextfilterContext)
{
varcontext=filterContext.HttpContext;
context.Session["IsStaticHtml"]=false;
stringpath=context.Server.MapPath("/Resource/Manage/Html/Home/Index.html");
if(System.IO.File.Exists(path))
{
stringhtml=System.IO.File.ReadAllText(path);
context.Response.Write(html);
context.Session["IsStaticHtml"]=true;
context.Response.End();
}
}
}
5.执行首页:
[MyFirstHome]
publicActionResultIndex()
{
View_Homeview_Home=null;
varIsStaticHtml=Convert.ToBoolean(Session["IsStaticHtml"]);
if(!IsStaticHtml)
{
view_Home=newView_Home();
using(BangLiEntitiesbangLi=newBangLiEntities())
{
view_Home.CommandAdExtendList=Dal.CommandAdDal.Instance(bangLi).GetInit().ToList();
view_Home.NewsExtendList=Dal.NewsDal.Instance(bangLi).GetInit().OrderByDescending(u=>u.AddDateTime).Take(5).ToList();
}
returnView(view_Home);
}
else
{
returnnull;
}
}
说明:可以让一个超链接或跳转地址直接跳转到一个html的静态页面,速度会更快;
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。