10.在Global全局文件中的Application_BeginRequest示例

只要有人访问本网站,都要执行全局文件的Application_BeginRequest事件。因此我们可以防盗链。

示例要求:凡不是网站本机登录的都给客户端提示,用图片显示。

分析:由于网页在加载时不是一次性全部加载,如先加载网页,再加载相关的js文件,再加载图片等,因此在客户端上有个图片元素,在此事件中判断请求的类型是否为图片并且是否是以localhost登录的,如果不是就发送客户端的另个图片。

开发步骤:

   1.在目录中放两个图片,一个图片为正常显示,另一个为禁用提示的图片

   2.新建一HTML页面,它的源码为:

  

复制代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <img src="imgs/pic.jpg" />
</body>
</html>
复制代码

 

   3.添加Global.asax文件,写入以下内容

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace GlobalTest
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
           if(HttpContext.Current.Request.Url.AbsolutePath.EndsWith(".jpg")&&HttpContext.Current.Request.UrlReferrer.Host!="localhost")
           {
               HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("~/imgs/forbid.png"));
               HttpContext.Current.Response.End();
           }

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}
复制代码

4.运行网页,用loaclhost显示为pic.jpg文件,如果在地址栏中改为127.0.0.1则会显示我们要的forbid.png文件,如下图

posted on   天上星  阅读(14541)  评论(0编辑  收藏  举报

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示