上一篇说到:为了可扩展与方便大伙,我定义了一个抽象类,先实现了三个正则用于截取标题,说明,和关键字。
抽象类代码简洁如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
public abstract class replacetextlistbase
{
/// <summary>
/// 将被返回的替换文本集合列表
/// </summary>
public dictionary<string, string> replacetextlist = new dictionary<string, string>();
/// 获取当前请求页面的url信息
public uri pageurl { get { return httpcontext.current.request.url; } }
/// 获取html的title的正则
public string titleregex { get { return "<title.*>.*</title>"; } }
public string titleformat(string titletext)
{
return "<title>" + titletext + "</title>";
}
/// 获取html的description的正则
public string descriptionregex { get { return "<meta[^<>]+name=[\"\']description[^<>]*[/]>"; } }
public string descriptionformat(string descriptiontext)
return "<meta id=\"description\" name=\"description\" content=\"" + descriptiontext + "\" />";
/// 获取html的keyword的正则
public string keywordregex { get { return "<meta[^<>]+name=[\"\']keywords[^<>]*[/]>"; } }
public string keywordformat(string keywordtext)
return "<meta id=\"keywords\" name=\"keywords\" content=\"" + keywordtext + "\" />";
/// 复写此方法,调用replacetextlist.add()方法后,return replacetextlist;
/// <returns></returns>
public virtual dictionary<string, string> getreplacetextlist()
return replacetextlist;
}
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
抽象类后,留下一个虚方法getreplacetextlist(), 这是重点
现在看一下我的示例中的子类的实现,继承自抽象类,复写虚方法:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
public class replacetextlist:replacetextlistbase
{
public override system.collections.generic.dictionary<string, string> getreplacetextlist()
replacetextlist.add(titleregex,titleformat("titleregex"));
replacetextlist.add(descriptionregex,descriptionformat("descriptionttest"));
replacetextlist.add(keywordregex,keywordformat("keywordadfdfdf"));
}
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
代码解析:
例子中的子类实现很简单,就复写了一个虚方法,最终页面的输出标题为:titleregex。其它两个同理。
如果要替换其它或过滤文件,只要写多几个add方法把要替换的文字给替换掉就行了,具体也可以结合下数据库或其它文件操作
另外说明:
例子上,直接就定死了标题输出为:titleregex,这里可以结合自己的需要,替换成任意字符串。
提示:抽象类里还留下了pageur吧,可以根据url查出title和description和keyword来实现自己的扩展。
另外给出一些我早期实现的思路:
建数据库表,对url主机头进行分类管理,自己定义替换字符等,最后查询与替换。