html的静态化与httphander使用
时间:2011-01-27 来源:漠北的天空
在aspx.cs页面中重写Render方法,解析成Html静态源码
/// <summary>
/// 重写Render方法,解析成Html静态源码
/// </summary>
protected override void Render(HtmlTextWriter writer)
{
TextWriter sw = new StringWriter();
base.Render(new HtmlTextWriter(sw));
string htmlName = test.html;
CreateHtml(htmlName, sw.ToString());
}
/// <summary>
/// 生成Html静态模板
/// </summary>
public void CreateHtml( string htmlName, string htmlBody)
{
StringReader sr = new StringReader(htmlBody);
StringWriter sw = new StringWriter();
string htmlLine = sr.ReadLine();
try
{
while (htmlLine != null)
{
// 去掉Asp.Net独有标记
if (!(htmlLine.IndexOf("<form") > 0 || htmlLine.IndexOf("__VIEWSTATE") > 0 || htmlLine.IndexOf("__EVENTVALIDATION") > 0 || htmlLine.IndexOf("</form>") > 0))
{
sw.WriteLine(htmlLine);
}
htmlLine = sr.ReadLine();
}
string path = HttpContext.Current.Server.MapPath("~/Html/7/");
//判断文件目录是否存在
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
//写入Html
using (StreamWriter fs = new StreamWriter(path + htmlName, false, Encoding.GetEncoding("UTF-8")))
{
try
{
fs.Write(sw.ToString());
}
catch (Exception ea)
{
// UserOperationLog("CreateHtml", "写入Html" + ea.Message);
}
finally
{
if (fs != null)
{
fs.Flush();
fs.Close();
}
}
}
HttpContext.Current.Response.Write(sw.ToString());
}
catch (Exception ex)
{
UserOperationLog("CreateHtml出现异常", ex.Message);
HttpContext.Current.Response.Write(ex.Message);
}
finally
{
HttpContext.Current.Response.End();
}
}
二.httpHander使用:
1.在web.config 中设置:
<httpHandlers>
<add verb="*" path="*.html" type="PortalHttpHandler,App_Code"/>
</httpHandlers>
即,如果url是以html结尾的,则跳转到App_Code下的PortalHttpHandler类中进行处理;
1. PortalHttpHandler.cs中,PortalHttpHandler类继承接口 IHttpHandler 如下:
public class PortalHttpHandler : IHttpHandler, IRequiresSessionState
{
public PortalHttpHandler()
{
// TODO: 在此处添加构造函数逻辑
}
#region IHttpHandler 成员
public bool IsReusable
{
get { return true; }
}
/// <summary>
/// Url请求处理
/// </summary>
/// <param name="context">上下文</param>
public void ProcessRequest(HttpContext context)
{
//对url传递过来的内容进行处理;
//处理完后进行跳转
ResponseHtmlCode(“test.html”,”test.aspx”,true)
}
#endregion
/// <summary>
/// 如果需要更新,直接跳转到相应的aspx页面,如果不需要更新跳转到对应的html页面
/// </summary>
/// <param name="context">上下文</param>
public void ResponseHtmlCode(string path, string tempUrl, bool IsUpdated)
{
if (IsUpdated)
{//如果需要更新,直接跳转到相应的aspx页面
HttpContext.Current.Server.Transfer(tempUrl);
}
else
{//如果不需要更新跳转到对应的html页面
StreamReader sr = null;
try
{
sr = new StreamReader(path);
HttpContext.Current.Response.Write(sr.ReadToEnd());
}
catch (Exception e)
{
//写日志
}
finally
{
sr.Close();
sr.Dispose();
HttpContext.Current.Response.End();
}
}
}
}