我有一个 IP 列表,这些 IP 不断爬取我们的实时站点,当它们使用不带参数的某些 URL 时抛出异常(因为 MVC 路由)。我想阻止这些 IP 地址并在可以获取它们后立即返回 404 not found 页面,但我不想在 IIS 中执行此操作,因为我想在我们的应用程序中记录遭遇。
我编写了一个包罗万象的路由处理程序,它使用自定义 MvcHandler 来检查列表并修改响应:
public class ApplicationRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
BlacklistedIPAddressHandler handler = new BlacklistedIPAddressHandler(Cache.WebsiteCache.GetBlacklistedIPList(), requestContext);
return handler;
}
}
public class BlacklistedIPAddressHandler : MvcHandler
{
List<IPBlacklistModel> blacklist;
public BlacklistedIPAddressHandler(List<IPBlacklistModel> Blacklist, RequestContext requestContext) : base(requestContext)
{
blacklist = Blacklist;
}
protected override IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state)
{
var ip = httpContext.Request.UserHostAddress;
if (blacklist != null &&
blacklist.Where(x => x.IP_ADDRESS.Contains(ip)).Count() > 0)
{
httpContext.Response.ClearHeaders();
httpContext.Response.Clear();
httpContext.Response.StatusCode = 404;
httpContext.Response.SuppressContent = true;
httpContext.Response.End();
}
return base.BeginProcessRequest(httpContext, callback, state);
}
}
然后实现如下:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = @"[^\.]*" }
).RouteHandler = new Helpers.Routing.ApplicationRouteHandler();
}
执行此操作时,在发送 HTTP 标头后,我不断收到服务器无法附加标头错误。可能有人知道为什么吗?