通过密匙验证反盗链(以mp3为例)

1:建立Handler.cs文件

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

/// <summary>
/// Handler 的摘要说明
/// </summary>
public class Handler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string key = context.Request.QueryString.ToString();
        string filename =MD5(Common.GetIp() + "123456);
        if (!key.Equals(filename))
        {           
            return;
        }
        else
        {
            context.Response.Expires = 0;
            context.Response.Clear();
            context.Response.ContentType = "audio/mpeg3";
            context.Response.WriteFile(context.Request.PhysicalPath);
            context.Response.End();
        }
    }   
    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}

2:播放音频的代码加入

string filename = MD5(Common.GetIp() + "123456");
 music = 路径 + "伤心泪 陈星.mp3?" + filename;

生成如下:

 <object classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"  type="application/x-oleobject" width="396" height="45" id="player" >
        <param name="autoStart" value="-1"/>
        <param name="url" value="http://www.ddd.com/伤心泪 陈星.mp3?30B668A5F6E3246CA4EA9EC829529FE6" />
        <param name="balance" value="0"/>
        <param name="currentPosition" value="0"/>
        <param name="currentMarker" value="0"/>
        <param name="enableContextMenu" value="true"/>
        <param name="enableErrorDialogs" value="false"/>
        <param name="enabled" value="true"/>
        <param name="fullScreen" value="false"/>
        <param name="invokeURLs" value="false"/>
        <param name="mute" value="false"/>
        <param name="playCount" value="1"/>
        <param name="DisplaySize" value="2"/>
        <param name="rate" value="1"/>
        <param name="uiMode" value="full"/>
        <param name="volume" value="90"/>
    </object>

3:配置IIS,对IIS的asp.net处理内容进行过滤,对.mp3文件指定同aspx相同的dll

4:web.config中加入 

<httpHandlers>
      <add verb="*" path="*.mp3" type="Handler,App_Code"/>
</httpHandlers>

原文地址:https://www.cnblogs.com/luluping/p/1809840.html