我正在尝试根据404 response为服务器上的所有网站上的某些请求生成HttpRequest.UserAgent
。
我在服务器的全局IHttpModule
中配置了web.config
,其中包含以下代码:
private void Application_BeginRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
if (isBot(context.Request.UserAgent))
{
System.Diagnostics.EventLog.WriteEntry(
"Application",
"\nBotRequestChecker -- request 404d\n" + "Url: " +
context.Request.Url + "\nUserAgent: " + context.Request.UserAgent,
EventLogEntryType.Information);
context.Response.StatusCode = 404;
context.Response.StatusDescription = "Not Found";
context.ApplicationInstance.CompleteRequest();
}
}
在浏览器中设置User-Agent
并访问页面会在事件日志中生成一个条目,但也会返回该页面,而不会显示404状态。
对我缺少什么的想法?
更新:
如果我将IHttpModule
添加到单个网站(在网站的web.config
中),IHttpModule
确实有效,而不是所有网站。
更新2: {{1}}仅适用于 IIS7 服务器上的单个网站,而不适用于 IIS6 。
答案 0 :(得分:0)
确保您已在模块的IHttpModule.Init()
实施中订阅了BeginRequest事件。这些事件在IHttpModule
实现中不会像在Global.asax中那样自动连接。
我最初也错过了关于全球web.config的一点。
在64位服务器上,您需要确保在所有ASP.NET版本中对32位和64位配置进行更改(取决于运行站点的位数)需要支持:
%windows%\Microsoft.NET\Framework\v2.0.50727\CONFIG\web.config
%windows%\Microsoft.NET\Framework64\v2.0.50727\CONFIG\web.config
%windows%\Microsoft.NET\Framework\v4.0.30319\CONFIG\web.config
%windows%\Microsoft.NET\Framework64\v4.0.30319\CONFIG\web.config
如果您同时定位IIS6和IIS7,则需要确保IIS6的<system.web>/<httpModules>
元素和IIS7的<system.webServer>/<modules>
元素都引用了该模块。