
免费推荐:IIS安装
这个类是基于 Microsoft.Web.Administration 写的一个简单封装:
PS: Microsoft.Web.Administration 可通过 Nuget 搜索安装。
public class IISAdministration
{
private readonly ServerManager serverManager;
public IISAdministration()
{
serverManager = new ServerManager();
}
public IEnumerable<WorkerProcess> GetWorkerProcesses()
{
return serverManager.WorkerProcesses;
}
public IEnumerable<string> GetSiteNames()
{
foreach (var item in GetWorkerProcesses())
{
yield return item.AppPoolName;
}
}
public ConfigurationElementCollection GetIpSecurityCollection(string site)
{
return GetConfigurationElementCollection("system.webServer/security/ipSecurity", site);
}
public ConfigurationElementCollection GetConfigurationElementCollection(string sectionName, string site = "")
{
var config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection section;
if (string.IsNullOrWhiteSpace(site))
{
section = config.GetSection(sectionName);
}
else
{
section = config.GetSection(sectionName, site);
}
return section.GetCollection();
}
public void CreateElement(ConfigurationElementCollection section, ConfigurationElement element)
{
section.Add(element);
serverManager.CommitChanges();
}
public void RemoveElement(ConfigurationElementCollection section, ConfigurationElement element)
{
section.Remove(element);
serverManager.CommitChanges();
}
public bool HasBlocked(string siteName, string ip)
{
var ipSecurityCollection = this.GetIpSecurityCollection(siteName);
for (int i = 0; i < ipSecurityCollection.Count; i++)
{
var element = ipSecurityCollection[i];
if ((string)element["ipAddress"] == ip)
{
return true;
}
}
return false;
}
public void FreeIP(string siteName, string ip)
{
if (!HasBlocked(siteName, ip))
{
return;
}
var ipSecurityCollection = this.GetIpSecurityCollection(siteName);
for (int i = 0; i < ipSecurityCollection.Count; i++)
{
var element = ipSecurityCollection[i];
if ((string)element["ipAddress"] == ip)
{
this.RemoveElement(ipSecurityCollection, element);
break;
}
}
}
public void BlockIP(string siteName, string ip)
{
if (HasBlocked(siteName, ip))
{
return;
}
var ipSecurityCollection = this.GetIpSecurityCollection(siteName);
var element = ipSecurityCollection.CreateElement("add");
element["ipAddress"] = ip;
element["allowed"] = false;
ipSecurityCollection.Add(element);
serverManager.CommitChanges();
}
}使用方法:
var iisAdministration = new IISAdministration();
iisAdministration.BlockIP("", "192.0.0.1");注意:
BlockIP第一个参数为站点名,如果空字符串,则直接添加到 IIS 根路径下的IP屏蔽。以上就是如何使用IIS API禁用IP访问的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号