devzero devzero - 3 months ago 25
ASP.NET (C#) Question

How can I add a new binding to the current IIS site from a mvc application

I have a multi tenant application where the administrators can add new customers from the GUI. This will set up a customer specific site where the url would be something like : customerName.mydomain.com. At the moment I then have to go into IIS to add that URL to the bindings for my site. How can I do this from the C# code?

IIS version is 7 or higher.

From answer below I ended up with the following:

You have to give write access to the folder "C:\Windows\System32\inetsrv\config\" to the user the Site is running under

var server = new ServerManager();
var site = server.Sites.FirstOrDefault(a => a.Name.Contains("mydomain"));
if (site != null)
{
site.Bindings.Add($"*:80:{customer}.mydomain.com", "http");
server.CommitChanges();
}

Answer

For IIS 7 and above there is an API https://blogs.msdn.microsoft.com/carlosag/2006/04/17/microsoft-web-administration-in-iis-7/

From the link:

ServerManager iisManager = new ServerManager();
iisManager.Sites[“NewSite”].Applications.Add(“/Sales”, “d:\\MyApp”);
iisManager.Update(); 

That should get you on the way