ASP AdRotator

用 AdRotator 组件轮播广告、Schedule 文件格式、点击统计。

Intermediate
Key PointsAdRotator 读一个 Schedule 文本文件,按权重随机挑一条广告输出成链接。

Schedule 文件

Text
REDIRECT /ads/redirect.asp
WIDTH 468
HEIGHT 60
BORDER 1
*
/ads/img/banner1.gif
https://example.com/promo1
春季促销,全场八折
20
/ads/img/banner2.gif
https://example.com/promo2
新品上市
40
/ads/img/banner3.gif
https://example.com/promo3
会员专享
40
LineMeaning
REDIRECT点击后先经过它,可统计再跳转
WIDTH / HEIGHT输出 img 标签的宽高
BORDER0 无边框
*之后每条广告四行
四行一组图片路径 / 目标链接 / 替代文字 / 权重

Weights are relative: 20, 40, 40 means the second and third appear about 40% of the time each. Writing 1, 2, 2 behaves identically.

页面里用

ASP
<%
    Dim ad
    Set ad = Server.CreateObject("MSWC.AdRotator")
    ad.Border = 0
    ad.Clickable = True
    ad.TargetFrame = "_blank"
    Response.Write ad.GetAdvertisement("/ads/schedule.txt")
    Set ad = Nothing
%>
Output
<a href="/ads/redirect.asp?url=https://example.com/promo2&image=/ads/img/banner2.gif"
   target="_blank">
  <img src="/ads/img/banner2.gif" alt="新品上市" width="468" height="60" border="0">
</a>

点击统计

ASP
<%-- /ads/redirect.asp --%>
<%
    Dim url, image, fso, ts
    url = Request.QueryString("url")
    image = Request.QueryString("image")

    ' 记一笔点击
    Set fso = Server.CreateObject("Scripting.FileSystemObject")
    Set ts = fso.OpenTextFile(Server.MapPath("/logs/ads.log"), 8, True)
    ts.WriteLine Now() & " | " & image & " | " & url & " | " & _
                 Request.ServerVariables("REMOTE_ADDR")
    ts.Close
    Set ts = Nothing
    Set fso = Nothing

    Response.Redirect url
%>
redirect.asp redirecting straight to the url parameter is an open redirect: an attacker can craft redirect.asp?url=https://phish that appears to originate from your domain. Validate against a domain allow-list.

替代方案

ASP
<%
    ' 自己实现:从数据库取广告,随机挑一条
    Dim rs, total, pick, acc
    Set rs = conn.Execute("SELECT id, img, url, alt, weight FROM ads WHERE active = 1")

    Randomize
    pick = Int(Rnd() * 100) + 1
    acc = 0
    Do While Not rs.EOF
        acc = acc + rs("weight")
        If pick <= acc Then
            Response.Write "<a href=""" & rs("url") & """ target=""_blank"">" & _
                "<img src=""" & rs("img") & """ alt=""" & _
                Server.HTMLEncode(rs("alt")) & """></a>"
            Exit Do
        End If
        rs.MoveNext
    Loop
%>

AdRotator dates from the 1990s: a plain-text config, no admin UI, no targeting. Real projects use a database and a few lines of random selection.

组件是否可用

ASP
<%
    On Error Resume Next
    Dim ad
    Set ad = Server.CreateObject("MSWC.AdRotator")
    If Err.Number <> 0 Then
        Response.Write "AdRotator 组件不可用(可能未安装 IIS 组件或 32/64 位不匹配)"
        Err.Clear
    End If
    On Error GoTo 0
%>

The MSWC.* components are 32-bit COM. A 64-bit IIS app pool cannot load them by default; you must enable "32-bit applications" on the pool, which makes the whole pool 32-bit.

Friends & Partners