3. 编码实现
由于本文提供全部的c#源码下载,所以本节仅对源码压缩包中的主要文件进行简要说明:
以下为引用的内容: DotCommon.WebsiteFilter │ DotCommonWebsiteFilter.cfg.xml │ WebsiteFilterConfiguration.cs │ WebsiteFilterHttpModule.cs ├─Util │ GlobesCache.cs │ XmlAttributeReader.cs └─WebsiteFilter IPMatchEngine.cs UrlMatchCondition.cs UrlMatchEngine.cs |
DotCommonWebsiteFilter.cfg.xml
运行参数配置文件
WebsiteFilterConfiguration.cs
配置文件实体类
WebsiteFilterHttpModule.cs
实现了System.Web.IHttpModule接口的自定义Http模块
GlobesCache.cs
全局缓存操控类
XmlAttributeReader.cs
xml节点属性读取器
IPMatchEngine.cs
IP匹配引擎
UrlMatchCondition.cs
Url匹配条件(与正则表达式匹配)
UrlMatchEngine.cs
Url匹配引擎
WebsiteFilterHttpModule.cs中BeginRequest自定义处理程序的核心代码如下:
以下为引用的内容: void context_BeginRequest(object sender, EventArgs e) { if (HttpContext.Current.Request.IsLocal)//忽略本地计算机请求 return; string ip = HttpContext.Current.Request.UserHostAddress; if (!WebsiteFilterConfiguration.GetConfig().PickedIPs.IsMatch(ip)) { //若在IP列表中找不到访客ip string rawUrl = HttpContext.Current.Request.RawUrl; UrlMatchEngine pu = WebsiteFilterConfiguration.GetConfig().PickedUrls; //列表包含当前url且列表为黑名单、列表不包含当前url且列表不为黑名单 时需转向 //换而言之,“配备结果”与“是否黑名单”取值一致时需转向 if (pu.IsMatch(rawUrl) == pu.IsBlacklist) { //非公开url自动重定向 HttpContext.Current.Response.Redirect(pu.ErrorPage); } } } |
4. 部署应用
4.1. DotCommonWebsiteFilter.cfg.xml配置文件
配置文件的根节点为DotCommon,所有配置信息均为WebsiteFilter节点的子项。PickedUrl节点对应Url列表,IsBlacklist(1是0否)指示是否为黑名单,ErrorPage指定错误提示页路径,其子节点add可重复出现,通过pattern属性指定正则表达式文本,上图所示配置表示仅网站首页(default.aspx)允许外网用户访问。
PickedIP节点对应IP列表,有效子节点包括add、remove、clear三项。以上图为例,第一个add指示内网ip为192.168.10.1、192.168.10.2、192.168.10.3、192.168.10.4、192.168.10.5五个;到第二行删除掉192.168.10.2、192.168.10.3、192.168.10.4还剩192.168.10.1、192.168.10.5两个;到第三行再添加上192.168.10.3,最终的内网IP列表为192.168.10.1、192.168.10.3、192.168.10.5三个。
4.2. 在企业网站中集成
配置好DotCommonWebsiteFilter.cfg.xml中的各项参数并拷贝到网站根目录。
拷贝DotCommon.WebsiteFilter.dll文件到网站bin目录。
在网站根目录下建立与配置文件中相对应的错误提示页(例如sorry.htm)。
修改Web.config在《httpModules》节点下注册WebsiteFilter模块,代码如下:
以下为引用的内容: <httpModules> <add name="WebsiteFilter" type="DotCommon.WebsiteFilterHttpModule, DotCommon.WebsiteFilter"/> </httpModules> |
分别从内网、外网访问企业网站查看运行效果。
结束语
本文仅针对具体需求阐述解决方案的构思过程,希望对读者能有所帮助,欢迎提出改进意见。
.
分页: [1] [2]
TAG: NET 环境 功能