.net 中HttpHandler的应用

  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>

 

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值