国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

Asp.net 圖片文件防盜鏈(尊重勞動成果)及BeginRequest事件學(xué)習(xí)

2024-07-10 13:17:53
字體:
供稿:網(wǎng)友
關(guān)于圖片盜鏈這個問題,畢竟是自己的勞動成功,很多人不希望別人就那么輕易地偷走了。 這個功能在很多的論壇上都具有,可能是因為盜鏈的行為太多了吧

反盜鏈的程序其實很簡單,熟悉ASP.NET 應(yīng)用程序生命周期的話很容易就可以寫一個,運用HttpModule在BeginRequest事件中攔截請求就ok了,剩下的工作就是過濾,再過濾!

如果不熟悉HttpModule的話,可以去MSDN上查閱,介紹非常詳細(xì),地址:ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_aspnetcon/html/f1d2910f-61d0-4541-8af8-c3c108ca351f.htm.這里就不廢話了

復(fù)制代碼 代碼如下:


private void Application_BeginRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
bool isSafe = true; //是否合法鏈接
string uri = context.Request.Url.AbsolutePath.ToLower();
if (uri.LastIndexOf(“.”) > 0 && context.Request.UrlReferrer != null)
{
string exp = uri.Substring(uri.LastIndexOf(“.”));
//這里是判斷文件后綴名是否在排除的文件類型列表之內(nèi)
bool isHas = ClassLibrary.RData.RString.StrIsIncUseSC(exp, config.ImgSafeType.Split(‘|'));
if (isHas)
{
string domainOutter = context.Request.UrlReferrer.Authority.ToLower(); //包含域名和端口
ArrayList arry = Common.Cache.GetDomainValid();//取系統(tǒng)定義的合法的域名綁定列表
isSafe = arry.Contains(domainOutter); //判斷當(dāng)前請求的域名是否在合法列表之內(nèi)
}
}
//下面就是不合法的時候的輸出了,如果有默認(rèn)替代圖片則輸出,如果沒有就生成一個,格式為。gif
if (!isSafe)
{
Bitmap img = null;
Graphics g = null;
MemoryStream ms = null;

try
{
string picPath = ClassLibrary.RPath.GetFullDirectory(“images/unlawful.gif”);
if (File.Exists(picPath))
{
img = new Bitmap(picPath, false);
}
else
{
img = new Bitmap(**, **);
g = Graphics.FromImage(img);
g.Clear(Color.White);
Font f = new Font(“宋體,黑體,Arial”, 9,FontStyle.Bold);
SolidBrush s = new SolidBrush(Color.Red);
g.DrawString(Resources.Message.LawlessLink, f, s, 1, 20);
img.Save(picPath, ImageFormat.Gif);
}
ms = new MemoryStream();
img.Save(ms, ImageFormat.Gif);
context.Response.ClearContent();
context.Response.ContentType = “image/Gif”;
context.Response.BinaryWrite(ms.ToArray());
context.Response.End();
}
catch
{ }
finally
{
if(g != null )
g.Dispose();
img.Dispose();
}
}
}


凡是有利必有害,這樣做最大的缺點就是增加了系統(tǒng)開銷,客戶端的每一請求都要過濾一遍,性能自然要打折扣了。不知道哪位朋友有更好的辦法,或者優(yōu)化的方法,一起來探討探討

實現(xiàn)文件放盜鏈的功能再續(xù):
首先添加一個全局文件 Global.asax
在 Application_BeginRequest中我們可以判斷Http報文頭中的UrlReferre是否來源本站。

復(fù)制代碼 代碼如下:


if (HttpContext.Current.Request.UrlReferrer != null)
{
if (HttpContext.Current.Request.Url.AbsolutePath.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) && HttpContext.Current.Request.UrlReferrer.Host != "localhost")
{
HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("~/jzdl.jpg"));
HttpContext.Current.Response.End();
}
}

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 河曲县| 夏河县| 垦利县| 昌平区| 白玉县| 会泽县| 万全县| 汾西县| 阿城市| 察哈| 澜沧| 固阳县| 高邮市| 乡宁县| 北流市| 互助| 合肥市| 安吉县| 房产| 孝感市| 德格县| 大埔区| 深州市| 九龙坡区| 云和县| 乐清市| 隆化县| 昌都县| 天水市| 邢台县| 沙湾县| 姚安县| 淮北市| 侯马市| 怀集县| 澄城县| 宣威市| 正阳县| 湖口县| 呼伦贝尔市| 安多县|