.net Core 实现web网站图片防盗连接源码实例

首次发布:2020-02-10 10:46
这里我用的是.net Core 3.1 以下是核心代码
public class RefuseStealingMiddleWare
{//转载请保留http://www.luofenming.com/show.aspx?id=ART2020021000001
    private readonly RequestDelegate _next;

    public RefuseStealingMiddleWare(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        string url = context.Request.Path.Value;

        if (url.Contains(".jpg")|| url.Contains(".png"))
        {
            string urlReferrer = context.Request.Headers["Referer"];
            if (string.IsNullOrWhiteSpace(urlReferrer))//直接访问
            {
                await this.SetForbiddenImage(context);//返回404图片
            }
            else if (!urlReferrer.Contains("localhost"))//非当前域名
            {
                await this.SetForbiddenImage(context);//返回404图片
            }
            else
            {
                await _next(context);//走正常流程
            }
        }
        else
        {
            await _next(context);//走正常流程
        }
    }
    /// <summary>
    /// 设置拒绝图片
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private async Task SetForbiddenImage(HttpContext context)
    {
        string defaultImagePath = "wwwroot/image/nopic.jpg";
        string path = Path.Combine(Directory.GetCurrentDirectory(), defaultImagePath);

        FileStream fs = File.OpenRead(path);
        byte[] bytes = new byte[fs.Length];
        await fs.ReadAsync(bytes, 0, bytes.Length);
        await context.Response.Body.WriteAsync(bytes, 0, bytes.Length);
    }
}

以下是Startup 下Configure的应用
app.UseMiddleware<RefuseStealingMiddleWare>();
//注意 应用要放在最前面

直接防问网站上的图片连接, 就会显示我们设置指定的图片,如果还是原来图片就刷新一下.

源码下载链接:https://pan.baidu.com/s/1kvxDVgIpbXpI-uqKsggFZA  提取码:31st 

视频讲解地址 https://www.bilibili.com/video/BV1bU4y1c7As