使用HttpHandler 来实现url路径伪静态

本文介绍了如何通过配置HttpHandlers节点和使用正则表达式在Web.config文件中实现URL路径的伪静态处理,从而优化网站的SEO和用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要在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);
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值