Adding a Website to IIS7 programmatically

Some time ago, I blogged about Adding an Application Pool to IIS7 programmatically. The result was a new Application Pool, that uses the Integrated Pipeline in IIS7.

In this post I will show you how to add a new Website, that uses the Application Pool from the other blog post.

I’ve loaded the Console Application I used to add the Application Pool, and moved the logic from Main to a method called AddApplicationPool, to split it up nicely. It is actually even easier to add a website programmatically. Below is the code for doing just that:

privatestaticvoid AddWebSite() { ServerManager mgr = new ServerManager(); if (!Directory.Exists(@"c:\inetpub\wwwroot\iis7test")) { Directory.CreateDirectory(@"c:\inetpub\wwwroot\iis7test"); } // Add a new Site to the server, configured to use our the iis7test home directory. Site site = mgr.Sites.Add("MyWebSite", @"c:\inetpub\wwwroot\iis7test", 80); // Set the application pool name of the site, to use the MyAppPool application pool. site.ApplicationDefaults.ApplicationPoolName = "MyAppPool"; // Clear all bindings. site.Bindings.Clear(); // Make the site listen to incoming HTTP requests using host header iis7test, on port 80. site.Bindings.Add("*:80:iis7test", "http"); // Set auto start to true. site.ServerAutoStart = true; // Commit the changes mgr.CommitChanges(); }

Notice how we add Bindings to the website. Bindings is the information that tells IIS7 when to serve our website. We use this string to configure bindings: *:80:iis7test. The first * tells IIS to listen on all IP addresses on your system. 80 is the port number, and iis7test is the host header value for this site.

To browse our website, we need to add iis7test to the computers hosts file (located in %WINDIR%\System32\Drivers\etc), and point it to

### The Integrated Programming model in IIS 7

IIS 7 comes with a bunch of improvements for developers. You can do a whole lot of exciting things even from web.config, but also from code.

To take advantage of the powerful integrated programming model, you need to set your application pool to use the Integrated pipeline mode. There’s no limit to what you can do.

I found a lot of great stuff in the book called Professional IIS 7 and ASP.NET Integrated Programming and learned a lot of useful stuff.

IIS 7 (or 7.5) is still the preferred way to develop, test and deploy ASP.NET applications, and as a developer you must stay up-to-date on what your tools and framework has to offer!