您的位置:首页 > 其它

.NET 实现ISAPI过滤器,指定类型文件防下载

2007-01-30 17:02 375 查看
using System;
using System.Web;
using System.Configuration;
namespace CheckDownload
{
#region Corp
// By : 公子哥
// .NET 实现ISAPI过滤器,文件防下载
#endregion
public class DownloadHandler:IHttpHandler,System.Web.SessionState.IRequiresSessionState
{
#region IHttpHandler 成员
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
HttpRequest req = context.Request;
//从Request对象中获取所请求文件的物理路径
string strNew = "";
string strtmp = req.PhysicalPath;
unsafe
{
fixed(char *pValue = strtmp)
{
char * pnew= pValue;
pnew=pnew+strtmp.LastIndexOf(".");
for (;*pnew !='\0';++pnew)
{
strNew+= Convert.ToString(*pnew);
}
}
}
//根据Session中UserName是否存在判断用户是否登陆
if (context.Session["UserName"] == null)
{
//未登陆
System.Web.HttpContext.Current.Server.Transfer(ConfigurationSettings.AppSettings["LoginShow"].ToString());
}
else
{
//防.bokee文件,如果有多个文件应加入多个文件判断
if (strNew.ToLower().Equals(ConfigurationSettings.AppSettings["FileTypes"].ToString().ToLower()))
{
System.Web.HttpContext.Current.Server.Transfer(ConfigurationSettings.AppSettings["Error"].ToString());
}
}
}
#endregion
}
}

以上代码编译CSC,例:
(脚本),相关路径应以您的实际环境而定
set MyPath=C:\Inetpub\wwwroot\isapitest
cd %MyPath%
csc /t:library /out:./bin/download.dll Class1.cs /unsafe
pause

接下来设置IIS对扩展名.bokee的映射,将.bokee的解析权交给aspnet_isapi.dll
动作选择为:全部

最后配置 web.config文件

<appSettings>
<add key="FileTypes" value=".bokee" /><!-- 要过滤的文件扩展名 -->
<add key="Error" value="./messageshow.html" /> <!-- 如果用户登陆但没有权限 -->
<add key="LoginShow" value="./loginshow.html" /> <!--用户未登陆时候的提示 -->

</appSettings>

<httpHandlers>
<add verb="*" path="*.bokee" type="CheckDownload.DownloadHandler, download" />
</httpHandlers>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: