需要在web.config中配置 httpHandlers节点:
<add verb="*" path="news/*.html" type="WebApplication2.HttpHandlerDemo"/>
<system.web>
<httpHandlers>
<add verb="*" path="news/*.html" type="WebApplication2.HttpHandlerDemo"/>
</httpHandlers>
。。。。
</system.web>
HttpHandlerDemo代码:
using System;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace WebApplication2
{
public class HttpHandlerDemo : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
string url = context.Request.RawUrl; //取到url路径
//获取news/1.html里面的1数字(正则表达式取到对应的id)
string uid = new Regex(@"/\d+.").Match(url).Value.Replace("/", "").Replace(".", "");
string path = context.Server.MapPath("~/news/" + uid + ".html"); //获取静态页面的物理路径
string tmpPath = context.Server.MapPath("~/news/templete.html"); //获取模板的物理路径
string tmphtml = getPath(tmpPath); //读取模板页,生成字符串
News news = getNewsById(uid); //通过id获取到一行新闻数据
//将字符串中的占位符替换成数据库得到的数据
tmphtml = tmphtml
.Replace("{$Title}", news.title)
.Replace("{$pubDate}", news.pubdate.ToString())
.Replace("{$content}", news.content);
Saves(path, tmphtml);//将字符串生成静态页面
context.Response.WriteFile(path);//输出
}
/// <summary>
/// 保存生成的静态页
/// </summary>
void Saves(string savepath, string savehtml)
{
//创建路径制定的文件
using (FileStream fs = new FileStream(savepath, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
{
sw.Write(savehtml);//将字符串写入到创建的文件里面
}
}
}
/// <summary>
/// 找到模板页
/// </summary>
string getPath(string path)
{
string str = string.Empty;
if (!File.Exists(path)) { throw new Exception("没有找到模板"); }
//如果有模板页,打开进行读取
using (FileStream fs = new FileStream(path, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs, Encoding.Default))
{
//字符串接收读取的读取的数据
str = sr.ReadToEnd();//读取完整的文件
}
}
return str;
}
/// <summary>
/// id找到一行新闻数据
/// </summary>
News getNewsById(string id)
{
DataTable dt = getTable(id);
News news = new News();
news.title = dt.Rows[0]["title"].ToString();
news.pubdate = DateTime.Parse(dt.Rows[0]["pubdate"].ToString());
news.content = dt.Rows[0]["content"].ToString();
return news;
}
DataTable getTable(string id)
{
string sql = string.Format("select * from news where id={0}", int.Parse(id));
return SqlHelper.GetTable(sql);
}
}
}