这个类是基于 Microsoft.Web.Administration
写的一个简单封装:
PS: Microsoft.Web.Administration
可通过 Nuget
搜索安装。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 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();
}
}
使用方法:
1 2var
iisAdministration =
new
IISAdministration();
iisAdministration.BlockIP(
""
,
"192.0.0.1"
);
注意:
BlockIP
第一个参数为站点名,如果空字符串,则直接添加到 IIS
根路径下的IP屏蔽。Copyright © 2013-2021 8a.hk All Rights Reserved. 八艾云 版权所有 中山市八艾云计算有限公司 粤ICP备14095776号