您的位置:首页 > 理论基础 > 计算机网络

.net 中HttpHandler的应用

2010-09-15 12:26 309 查看
HttpHandler 其实就是处理对某种特定文件类型的请求,比如在.net中你可以处理.aspx的页面请求,从而使整个页面处理结果替换输出.

一.请求网站页面的url地址是http的则换成https的

1.建立UrlHander 类实现 IHttpHandler接口

代码:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace com.migosoft.bj.i5sc.webpages.webUtil
{
public class UrlHander : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{

if (context.Request.Url.ToString().ToLower().Contains("http://"))
{
context.Response.Redirect("https://www.test.com/" + context.Request.Url.AbsolutePath.ToLower().ToString());
}
}
public bool IsReusable
{
get { return true; }
}

}
}

2.Web.config配置文件添加 <httpHandlers>

<httpHandlers>
<add verb="*" path="*.aspx" type="命名空间.UrlHander,程序集名称" />
</httpHandlers>

verb"*"表示对所有(get,post)请求进行处理。Path指明对相应的文件进行处理,"*.aspx"表示会对ASPX页面的请求进行处理

二.asp.net HttpHandler实现图片防盗链

Step.1:创建文件 CustomHandler.cs,代码如下:

using System;
using System.Web;

namespace CustomHandler{
public class JpgHandler : IHttpHandler{
public void ProcessRequest(HttpContext context){
// 获取文件服务器端物理路径
string FileName = context.Server.MapPath(context.Request.FilePath);
// 如果UrlReferrer为空,则显示一张默认的禁止盗链的图片
if (context.Request.UrlReferrer.Host == null){
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/error.jpg");
}else{
// 如果 UrlReferrer中不包含自己站点主机域名,则显示一张默认的禁止盗链的图片
if (context.Request.UrlReferrer.Host.IndexOf("yourdomain.com") > 0){
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile(FileName);
}else{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/error.jpg");
}
}
}

public bool IsReusable{
get{ return true; }
}
}
}

Step.2 编译这个文件 代码如下:

csc /t:library /r:System.Web.dll CustomHandler.cs

Step.3 将编译好的 CustomHandler.dll 拷贝到站点的 Bin 目录下。
Step.4 在Web.Config 中注册这个Handler。

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