Httphandler对象的防盗链使用
1准备两个asp.net的空项目
并准备像如图所示的文件夹等
先创建一个类继承IHttphandler代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1
{
public class handel : IHttpHandler
{
public bool IsReusable => true;
public void ProcessRequest(HttpContext context)
{
Uri p1 = context.Request.UrlReferrer;
Uri p2 = context.Request.Url;
if (p1.Host!=p2.Host||p1.Port!=p2.Port)
{
string e = context.Request.PhysicalApplicationPath + "error/3.jpg";
context.Response.WriteFile(e);
}
else
{
context.Response.WriteFile(context.Request.PhysicalPath);
}
}
}
}
在config文件中修改配置文件
<?xml version="1.0" encoding="utf-8"?>
<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
//配置文件的书写
<system.webServer>
<handlers>
<add path="images/*" name="test" verb="*" type="WebApplication1.handel"/>
</handlers>
</system.webServer>
</configuration>
拖拽图片指web h5代码中
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Show.aspx.cs" Inherits="WebApplication1.Show" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<style>
img{
height:100px;
width:100px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<img src="images/1.jpg" /><img src="images/2.jpg" />
</div>
</form>
</body>
</html>
在另一个 web窗体代码如下
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="web.aspx.cs" Inherits="ImageLink.web" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<style>
img{
height:100px;
width:100px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<img src="https://localhost:44307/images/2.jpg" />
</div>
</form>
</body>
</html>
启动两个项目的初始项目如图就会实现防盗链的功能