隐藏

C#给IIS添加禁止IP限制

发布:2022/8/19 11:31:05作者:管理员 来源:本站 浏览次数:930

/// <summary>
/// 给IIS添加禁止IP限制
/// 仅针对iis 7及以上版本
/// 首先需要引入Microsoft.Web.Administration.dll
/// 该文件位置在windows2008的\Windows\System32\inetsrv目录下
/// 注意:生成的EXE文件必须以管理员身份运行
/// </summary>
/// <param name="ip"></param>
private static void banIP(string ip)
{
    using (ServerManager serverManager = new ServerManager())
    {
        Configuration config = serverManager.GetApplicationHostConfiguration();
        ConfigurationSection ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity");
        ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection();
        ConfigurationElement addElement = ipSecurityCollection.CreateElement("add");
        addElement["ipAddress"] = ip;
        ipSecurityCollection.Add(addElement);
        serverManager.CommitChanges();
    }
}