In my earlier post How to get list of applications in IIS programatically using .Net, I discussed how to automate IIS management using managed API. One of the common task or action that lot of applications perform is block or unblock IP addresses of users that may be violating some rules or trying to attack your site. Here is code sample that will answer following questions.
static void BlockIpAddress(string site, string ip) { var serverManager = new ServerManager(); var hostConfig = serverManager.GetApplicationHostConfiguration(); // Get ipSecurity section in configuration. var ipSecuritySection = hostConfig.GetSection("system.webServer/security/ipSecurity", site); var configElements = ipSecuritySection.GetCollection(); // Check if this ip address is already blocked. var ipExists = false; foreach (var elem in configElements) { if (elem.ElementTagName == "add") { var ipaddr = elem.Attributes["ipAddress"]; if (null == ipaddr) { continue; } if (ipaddr.Value == ip) { // Check value of "allowed" attribute. if ((bool)elem.Attributes["allowed"].Value == true) { // Simple change this attribute to false and we are done. elem.Attributes["allowed"].Value = false; break; } } } } if (!ipExists) { // Create new element and add it to collection. var newElement = configElements.CreateElement("add"); newElement.Attributes["ipAddress"].Value = ip; newElement.Attributes["allowed"].Value = false; configElements.Add(newElement); } serverManager.CommitChanges(); }
How to plan CCSP Exam preparation
Develop a MongoDB pipeline to transform data into time buckets
Alert and Confirm pop up using BootBox in AngularJS
AngularJS Grouped Bar Chart and Line Chart using D3
How to lock and unlock account in Asp.Net Identity provider
2024 © Byteblocks, ALL Rights Reserved. Privacy Policy | Terms of Use