在ASP.NET中,利用ASHX技术实现图片防盗链是一种常见且有效的方法,ASHX文件是ASP.NET中的一个模块,可以处理HTTP请求,而不需要创建完整的ASP.NET页面,以下是如何在ASP.NET中使用ASHX实现图片防盗链的详细步骤和代码示例。
ASHX简介
ASHX文件是一种特殊的ASP.NET模块,可以用来处理HTTP请求,与ASPX页面不同,ASHX文件不依赖于ASP.NET页面框架,因此可以更灵活地处理各种HTTP请求。
实现图片防盗链的步骤
创建ASHX文件
在Visual studio中创建一个新的ASHX文件,这可以通过右键点击项目文件夹,选择“添加” -> “新建项”,然后选择“ASHX文件”来完成。
配置Web.config
在Web.config文件中,确保部分中启用了
httpModules
和配置,以便使用ASHX。
编写ASHX代码
在ASHX文件中,编写代码以处理图片请求,并检查请求是否来自合法的域名。
using System;using System.IO;using System.Web;public class ImageHandler : IHttpHandler{public void ProcessRequest(HttpContext context){context.Response.ContentType = "image/jpeg";string imagePath = context.Request.QueryString["path"];if (string.IsNullOrEmpty(imagePath)){context.Response.StatusCode = 404;return;}// 设置允许的域名列表string AllowedDomains = "example.com, anotherdomain.com";string referrer = context.Request.ServerVariables["HTTP_REFERER"];if (string.IsNullOrEmpty(referrer) || !allowedDomains.Contains(referrer)){context.Response.StatusCode = 403;return;}// 读取图片文件byte[] imageBytes = File.ReadAllBytes(imagePath);context.Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);}public bool IsReusable{get { return false; }}}
使用ASHX文件
您可以通过在URL中指定图片路径来访问图片,
表格:代码解析
| 代码部分 | 功能描述 |
|---|---|
context.Response.ContentType = "image/jpeg";
|
设置响应内容类型为JPEG图片 |
string imagePath = context.Request.QueryString["path"];
|
从查询字符串中获取图片路径 |
string allowedDomains = "example.com, anotherdomain.com";
|
定义允许访问图片的域名列表 |
string referrer = context.Request.ServerVariables["HTTP_REFERER"];
|
|
byte[] imageBytes = File.ReadAllBytes(imagePath);
|
读取图片文件到内存 |
context.Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);
|
将图片数据写入响应输出流 |
Q1: ASHX文件与ASPX页面的主要区别是什么?
A1: ASHX文件不依赖于ASP.NET页面框架,因此可以更灵活地处理HTTP请求,而不需要完整的页面结构,它主要用于处理特定类型的请求,如图片、文件下载等。
Q2: 如何测试图片防盗链功能?
怎样编写带有图片的程序
在中编写上传图片并同时生成带有版权信息的缩略图程序<%@ Page Language=C# ResponseEncoding=gb2312 %><%@ import Namespace=System %><%@ import Namespace= %><%@ import Namespace= %><%@ import Namespace= %>
asp.net和JQuery EasyUI DataGrid的数据交互问题
JQuery 与后台交付有get和post两种方法,我这里给你简介绍一下吧:
get方法:$(?userName=123,function(data){
//后台地址 userName参数 123参数值
//data是从后台返回来的数据
post方法:
$(,{userName:你好},function(data){
// //后台地址 userName参数 123参数值
//data是从后台返回来的数据
using System;using ;using SQLLibary;using ;using ;
public class index : IHttpHandler {
public void ProcessRequest (HttpContext context) {
= text/plain;
string type = [userName];
}public bool IsReusable {get {return false;}}
有什么不懂可以追问!有空就帮你解答!
asp上传图片源码
<%class clsUp 文件上传类------------------------Dim Form,FileDim AllowExt_ 允许上传类型(白名单)Dim NoAllowExt_ 不允许上传类型(黑名单)Private oUpFilestream 上传的数据流Private isErr_ 错误的代码,0或true表示无错Private ErrMessage_ 错误的字符串信息Private isGetData_ 指示是否已执行过GETDATA过程------------------------------------------------------------------类的属性Public Property Get VersionVersion=Version 2004End PropertyPublic Property Get isErr 错误的代码,0或true表示无错isErr=isErr_End PropertyPublic Property Get ErrMessage 错误的字符串信息ErrMessage=ErrMessage_End PropertyPublic Property Get AllowExt 允许上传类型(白名单)AllowExt=AllowExt_End PropertyPublic Property Let AllowExt(Value) 允许上传类型(白名单)AllowExt_=LCase(Value)End PropertyPublic Property Get NoAllowExt 不允许上传类型(黑名单)NoAllowExt=NoAllowExt_End PropertyPublic Property Let NoAllowExt(Value) 不允许上传类型(黑名单)NoAllowExt_=LCase(Value)End Property----------------------------------------------------------------类实现代码初始化类Private Sub Class_InitializeisErr_ = 0NoAllowExt= 黑名单,可以在这里预设不可上传的文件类型,以文件的后缀名来判断,不分大小写,每个每缀名用;号分开,如果黑名单为空,则判断白名单NoAllowExt=LCase(NoAllowExt)AllowExt= 白名单,可以在这里预设可上传的文件类型,以文件的后缀名来判断,不分大小写,每个后缀名用;号分开AllowExt=LCase(AllowExt)isGetData_=falseEnd Sub类结束Private Sub Class_Terminate on error Resume Next清除变量及对像 Form = File = oUpFileStream = NothingEnd Sub分析上传的数据Public Sub GetData (MaxSize)定义变量on error Resume Nextif isGetData_=false then Dim RequestBindate,sSpace,bCrLf,sInfo,iInfoStart,iInfoEnd,tStream,iStart,oFileInfoDim sFormValue,sFileNameDim iFindStart,iFindEndDim iFormStart,iFormEnd,sFormName代码开始If < 1 Then 如果没有数据上传isErr_ = 1ErrMessage_=没有数据上传Exit SubEnd IfIf MaxSize > 0 Then 如果限制大小If > MaxSize ThenisErr_ = 2 如果上传的数据超出限制大小ErrMessage_=上传的数据超出限制大小Exit SubEnd IfEnd IfSet Form = () = 1Set File = () = 1Set tStream = ()Set oUpFileStream = () = = () = 0RequestBinDate = iFormEnd = = ChrB (13) & ChrB (10)取得每个项目之间的分隔符sSpace = MidB (RequestBinDate,1, InStrB (1,RequestBinDate,bCrLf)-1)iStart = LenB(sSpace)iFormStart = iStart+2分解项目DoiInfoEnd = InStrB (iFormStart,RequestBinDate,bCrLf & bCrLf)+ = = = tStream, = = = gb2312sInfo = 取得表单项目名称iFormStart = InStrB (iInfoEnd,RequestBinDate,sSpace)-1iFindStart = InStr (22,sInfo,name=,1)+6iFindEnd = InStr (iFindStart,sInfo,,1)sFormName = Mid (sinfo,iFindStart,iFindEnd-iFindStart)如果是文件If InStr (45,sInfo,filename=,1) > 0 ThenSet oFileInfo = new clsFileInfo取得文件属性iFindStart = InStr (iFindEnd,sInfo,filename=,1)+10iFindEnd = InStr (iFindStart,sInfo,&vbCrLf,1)sFileName = Mid (sinfo,iFindStart,iFindEnd-iFindStart) = GetFileName(sFileName) = GetFilePath(sFileName) = GetFileExt(sFileName)iFindStart = InStr (iFindEnd,sInfo,Content-Type: ,1)+14iFindEnd = InStr (iFindStart,sInfo,vbCr) = Mid(sinfo,iFindStart,iFindEnd-iFindStart) = = iFormStart -iInfoEnd = sFormName,oFileInfoelse如果是表单项目 = = = iInfoEnd tStream, = = = gb2312sFormValue = (sFormName) ThenForm (sFormName) = Form (sFormName) & , & sFormName,sFormValueEnd IfEnd = iFormStart+iStart+2如果到文件尾了就退出Loop Until (iFormStart+2) >= iFormEnd RequestBinDate = Set tStream = NothingisGetData_=trueend ifEnd Sub保存到文件,自动覆盖已存在的同名文件Public Function SaveToFile(Item,Path)SaveToFile=SaveToFileEx(Item,Path,True)End Function保存到文件,自动设置文件名Public Function AutoSave(Item,Path)AutoSave=SaveToFileEx(Item,Path,false)End Function保存到文件,OVER为真时,自动覆盖已存在的同名文件,否则自动把文件改名保存Private Function SaveToFileEx(Item,Path,Over)On Error Resume NextDim oFileStreamDim tmpPathDim nohack 防黑缓冲isErr=0Set oFileStream = CreateObject () = = = File(Item) oFileStream,File(Item)=split(path,.) 重要修改,防止黑客\0断名伪装!!!tmpPath=nohack(0)&.&nohack(ubound(nohack)) 重要修改,防止黑客\0断名伪装!!!if Over thenif isAllowExt(GetFileExt(tmpPath)) tmpPath,2ElseisErr_=3ErrMessage_=该后缀名的文件不允许上传!End ifElsePath=GetFilePath(Path)if isAllowExt(File(Item)) ()nohack=split(Path&GetNewFileName()&.&File(Item),.) 重要修改,防止黑客\0断名伪装!!!tmpPath=nohack(0)&.&nohack(ubound(nohack)) 重要修改,防止黑客\0断名伪装!!! tmpPathloop Until < PathElseisErr_=3ErrMessage_=该后缀名的文件不允许上传!End ifEnd oFileStream = Nothingif isErr_=3 then SaveToFileEx= else SaveToFileEx=GetFileName(tmpPath)End Function取得文件数据Public Function FileData(Item)isErr_=0if isAllowExt(File(Item)) = File(Item) = (File(Item))ElseisErr_=3ErrMessage_=该后缀名的文件不允许上传!FileData=End ifEnd Function取得文件路径Public function GetFilePath(FullPath)If FullPath <> ThenGetFilePath = Left(FullPath,InStrRev(FullPath, \))ElseGetFilePath = End IfEnd function取得文件名Public Function GetFileName(FullPath)If FullPath <> ThenGetFileName = mid(FullPath,InStrRev(FullPath, \)+1)ElseGetFileName = End IfEnd function取得文件的后缀名Public Function GetFileExt(FullPath)If FullPath <> ThenGetFileExt = LCase(Mid(FullPath,InStrRev(FullPath, .)+1))ElseGetFileExt = End IfEnd function取得一个不重复的序号Public Function GetNewFileName()dim ranNumdim dtNowdtNow=Now()ranNum=int(*rnd)+GetNewFileName=year(dtNow) & right(0 & month(dtNow),2) & right(0 & day(dtNow),2) & right(0 & hour(dtNow),2) & right(0 & minute(dtNow),2) & right(0 & second(dtNow),2) & ranNumEnd FunctionPublic Function isAllowExt(Ext)if NoAllowExt= thenisAllowExt=cbool(InStr(1,;&AllowExt&;,LCase(;&Ext&;)))elseisAllowExt=not CBool(InStr(1,;&NoAllowExt&;,LCase(;&Ext&;)))end ifEnd FunctionEnd Class----------------------------------------------------------------------------------------------------文件属性类Class clsFileInfoDim FormName,FileName,FilePath,FileSize,FileMIME,FileStart,FileExtEnd Class%>














发表评论