We had an issue that we need to add or remove IIS 7 or IIS 7.5 additional bindings on one web application and we wanted to do this from one of our ASP.NET MVC applications.
It is possible so you need to use IIS system program appcmd.exe (you can find it in C:\Windows\System32\inetsrv\ (we suggest you to put this into your PATH variable)
Adding additional bindings
You want to add your-subdomain.your-domain.com binding to your IIS 7 app named your-domain.com
C:\Windows\System32\inetsrv\appcmd set site /site.name: your-domain.com /+bindings.[protocol='http',bindingInformation='*:80:your-subdomain.your-domain.com']
Removing existing bindings
You want to remove your-subdomain.your-domain.com binding from your IIS 7 app named your-domain.com (please notice - sign in front of bindings word)
C:\Windows\System32\inetsrv\appcmd set site /site.name: your-domain.com /-bindings.[protocol='http',bindingInformation='*:80:your-subdomain.your-domain.com']
And that’s it but if you want to run it from ASP.NET you could try to use Process and ProcessInfo classes to run DOS command but there are some permissions problems (we didn’t investigated much).
Other (alternative way that we tried is directly from the code)
You will need to reference this DLL: c:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll
using (ServerManager serverManager = new ServerManager())
{
if (serverManager.Sites == null)
throw new SimpleException("There are no IIS applications!");
var esponceApp = serverManager.Sites.FirstOrDefault(
x => x.Name == Settings.IISAppName);
if (esponceApp != null)
{
BindingCollection bindingCollection = esponceApp.Bindings;
Binding binding = bindingCollection.CreateElement("binding");
binding["protocol"] = "http";
binding["bindingInformation"] =
string.Format(@"{0}:{1}:{2}", "*", "80", this.DomainName);
//Remove this binding if already exists.
int oldBindingIndex = -1;
int bindingIndex = -1;
foreach (Binding currentBinding in esponceApp.Bindings)
{
if (currentBinding.BindingInformation ==
binding["bindingInformation"].ToString())
{
bindingIndex = esponceApp.Bindings.IndexOf(currentBinding);
}
if (!string.IsNullOrEmpty(oldDomainName) &&
currentBinding.BindingInformation ==
string.Format(@"{0}:{1}:{2}", "*", "80", oldDomainName))
{
oldBindingIndex = esponceApp.Bindings.IndexOf(currentBinding);
}
}
if (bindingIndex != -1)
{
esponceApp.Bindings.RemoveAt(bindingIndex);
}
if (oldBindingIndex != bindingIndex && oldBindingIndex != -1)
{
esponceApp.Bindings.RemoveAt(oldBindingIndex);
}
//Add this bindings
bindingCollection.Add(binding);
serverManager.CommitChanges();
}
}
}
catch
{
throw new SimpleException("Could not add binding into IIS application!");
}
Important!
Set identity of your app’s Application Domain from Advanced Settings > Process Model > Identity > Change “ApplicationPoolIdentity” to “Local System”
Investigate also security implications if you are not running this in Intranet….
