webform的图片防盗链

最近用到域的问题,不是同一主机的请求将不允许请求此页面。

这其实和图片防盗链的本质是一样的。

通过两个属性:由于当时用的aspx视图引擎,所以需要通过HttpContext.Current才能拿到httpcontext对象。

通过Httpcontext.Current.Request.UrlReferrer属性,指的是:是谁来请求。

HttpContext.Current.Request.Url属性,指的是:谁被请求。

如果这两个URI的主机名和端口号一直,则表示来自同一主机。

            //获取有关客户端上次请求的URL信息,该请求链接到当前的URL
            //表示是谁去请求
            string urlReferrer = HttpContext.Current.Request.UrlReferrer.Host.ToString();
            //获取有关当前请求的URL
            //表示请求谁
            string url = HttpContext.Current.Request.Url.Host.ToString();
            Uri.Compare(HttpContext.Current.Request.UrlReferrer, HttpContext.Current.Request.Url, UriComponents.HostAndPort, UriFormat.SafeUnescaped, StringComparison.CurrentCultureIgnoreCase);

  

关于图片防盗链实现的方案:

在项目中,图片的src不要直接写,可以通过一个方法去请求,在后台接受这个请求,

在做一样的判断,如果主机一样则返回正确的图片地址,如果不是则做相应的处理。

下面是官网的信息:

Return Value

Type: System.Int32

An Int32 value that indicates the lexical relationship between the compared Uri components.

Value

Meaning

Less than zero

uri1 is less than uri2.

Zero

uri1 equals uri2.

Greater than zero

uri1 is greater than uri2.

追加:

Uri.Compare的返回值为int类型,

0:表示两个相等。

大于0:表示前者大于后者。

小于0:表示前者小于后者。

原文地址:https://www.cnblogs.com/xiaoai123/p/7246795.html