你可以寫一個自定義的ASP.Net HttpModule,就像我爲我的網站所做的那樣,禁止一些流氓機器人。代碼如下:
public class UserAgentBasedRedirecter : IHttpModule
{
private static readonly Regex _bannedUserAgentsRegex = null;
private static readonly string _bannedAgentsRedirectUrl = null;
static UserAgentBasedRedirecter()
{
_bannedAgentsRedirectUrl = ConfigurationManager.AppSettings["UserAgentBasedRedirecter.RedirectUrl"];
if (String.IsNullOrEmpty(_bannedAgentsRedirectUrl))
_bannedAgentsRedirectUrl = "~/Does/Not/Exist.html";
string regex = ConfigurationManager.AppSettings["UserAgentBasedRedirecter.UserAgentsRegex"];
if (!String.IsNullOrEmpty(regex))
_bannedUserAgentsRegex = new Regex(regex, RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
#region Implementation of IHttpModule
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += RedirectMatchedUserAgents;
}
private static void RedirectMatchedUserAgents(object sender, System.EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (_bannedUserAgentsRegex != null &&
app != null && app.Request != null && !String.IsNullOrEmpty(app.Request.UserAgent))
{
if (_bannedUserAgentsRegex.Match(app.Request.UserAgent).Success)
{
app.Response.Redirect(_bannedAgentsRedirectUrl);
}
}
}
public void Dispose()
{ }
#endregion
}
您需要在web.config中註冊它並指定用於匹配用戶代理字符串的正則表達式。這裏有一個我曾經禁止msnbot/1.1流量:
<configuration>
<appSettings>
<add key="UserAgentBasedRedirecter.UserAgentsRegex" value="^msnbot/1.1" />
</appSettings>
...
<system.web>
<httpModules>
<add name="UserAgentBasedRedirecter" type="Andies.Web.Traffic.UserAgentBasedRedirecter, Andies.Web" />
</httpModules>
</system.web>
</configuration>
那麼,該網站是足夠小,使IIS日誌不是一個perf。問題;它主要是噪聲,我不介意避免 - 但這種解決方案正是我所希望的 - 一些可中止某些請求的可配置模塊。我會研究它,謝謝! – 2009-07-24 08:38:03
你知道是否有可能爲多個機器人創建一個規則? – UpTheCreek 2011-02-11 09:14:15
@UpTheCreek它是一種模式,只要你有一個正則表達式來標識你想要查找的所有機器人,你就可以將它插在那裏。不過,我會小心的,如果你不小心,殺死正常的流量似乎有點危險。 – 2015-07-24 15:19:05