Freigeben über


Microsoft.Web.Administration in IIS 7

While creating the new administration stack in IIS 7, we were looking into the different ways users could manipulate the server configuration as well as the new runtime information available in IIS 7 (Internally we call this RSCA-Runtime State and Control API) from managed code, and we realized we needed to provide a simpler and more straight forward API that developers could consume from managed code. Microsoft.Web.Administration is the answer to this problem. This API is designed to be simple to code against in an “intellisense-driven” sort of way. At the root level a class called ServerManager exposes all the functionality you will need.

To show the power and simplicity of this API, let’s look at some samples below. To try this samples just create a new Console Application in Visual Studio and add a reference to Microsoft.Web.Administration.dll that can be found at IIS directory (%WinDir%\System32\InetSrv).
Please note that the following code is based on Windows Vista Beta 2 code and will likely change for the release candidate versions of Windows Vista since we have planned several enhancements to simplify the API and expose more features into it.
The following picture shows the main objects (excluding Configuration related classes).
 
Microsoft.Web.Administration
Creating a Site
 

ServerManager iisManager = new ServerManager();
iisManager.Sites.Add("NewSite", "http", "*:8080:", "d:\\MySite");
iisManager.Update();

This basically creates an instance of the ServerManager class and uses the Add method in the Sites collection to create a new site named "NewSite" listening at port 8080 using http protocol and content files are at d:\MySite.
One thing to note is that calling Update is a requirement since that is the moment when we persist the changes to the configuration store.
After running this code you have now a site that you can browse using https://localhost:8080

Adding an Application to a site

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

This sample uses the Sites collection Indexer to get NewSite site and uses the Applications collection to add a new https://localhost:8080/Sales application.

Creating a Virtual Directory

ServerManager iisManager = new ServerManager();
Application app = iisManager.Sites["NewSite"].Applications["/Sales"];
app.VirtualDirectories.Add("/VDir", "d:\\MyVDir");
iisManager.Update();

Runtime State and Control

Now, moving on to the new Runtime state and control information we also expose in this objects information about their current state as well as the ability to modify them. For example, we expose the list of W3WP processes running (Worker processes) and what I think is really cool, we even expose the list of requests currently running. Stopping a Web Site

ServerManager iisManager = new ServerManager();
iisManager.Sites["NewSite"].Stop();

Recyciling an Application Pool

ServerManager iisManager = new ServerManager();
iisManager.ApplicationPools["DefaultAppPool"].Recycle();

Getting the list of executing requests

ServerManager iisManager = new ServerManager();
foreach(WorkerProcess w3wp in iisManager.WorkerProcesses) {
Console.WriteLine("W3WP ({0})", w3wp.ProcessId);

foreach (Request request in w3wp.GetRequests(0)) {
Console.WriteLine("{0} - {1},{2},{3}",
request.Url,
request.ClientIPAddr,
request.TimeElapsed,
request.TimeInState);
    }
}

Another big thing on this API is the ability to edit the “.config” files using a simple API, this includes the ability of modifying the main applicationHost.config file from IIS, web.config files from asp.net as well as machine.config and other config files (such as administration.config). However I will talk about them in a future post.

Comments

  • Anonymous
    April 16, 2006
    That might possibly be the coolest thing I've ever seen IIS do.
  • Anonymous
    April 20, 2006
    Its Wonderful and very cool.
    special thanks to Mr. carlos, Microsoft and Microsoft communities.

  • Anonymous
    April 20, 2006
    Waauuu, we will be saving so many lines of code and using this extensive.
  • Anonymous
    April 20, 2006
    Does this modify the (what used to be) metabase? When dealing with several web servers in a cluster, will I still need to sync the metabases (or .config files) across nodes, or can I finally centralize all this on a NAS via UNC?
  • Anonymous
    April 21, 2006
    The comment has been removed
  • Anonymous
    April 21, 2006
    The comment has been removed
  • Anonymous
    April 23, 2006
    O Scott Guthrie, do time de produtos Web da Microsoft, escreveu um post bem interessante sobre as novidades...
  • Anonymous
    April 23, 2006
    The comment has been removed
  • Anonymous
    April 24, 2006
    The comment has been removed
  • Anonymous
    April 24, 2006
    How about adding a "re-read config files" function to allow central config storage and after editing the config, telling each machine to re-read the file to flush the servers internal cache?
  • Anonymous
    April 24, 2006
    Not a bad idea, considering change notification doesnt work on metabase.xml.
  • Anonymous
    April 25, 2006
    Прошли старые добрые деньки. Реестр закапывают в землю, бинарные форматы закапыв
  • Anonymous
    April 25, 2006
    Yes you can create application pools as well as enumerate, remove them and even recycle them.
  • Anonymous
    April 27, 2006
    ну и слава богу, тока блин, когда еще смогу перетащить клиентов на 7ку...
  • Anonymous
    May 16, 2006
    Carlos Aguilar, del equipo de IIS 7 y desarrollador de la nueva consola y el nuevo API de administración...
  • Anonymous
    May 16, 2006
    Before the boom of web and internet, HTTP was not so common is everyday life. When internet became more...
  • Anonymous
    May 20, 2006
    Is there a way to Push data to client (Push Server ) using IIS 7? (ex live stock update !)
  • Anonymous
    May 21, 2006
    IIS7 is a major upgrade of IIS, and will ship in both Windows Vista as well as Windows Longhorn Server. ...
  • Anonymous
    March 29, 2007
    <a href=' http://filmsmovies.jedo.info/action-movie-downloads.html '>action movie downloads</a>
  • Anonymous
    August 26, 2007
    ServerManager iisManager = new ServerManager();iisManager.Sites.Add("NewSite", "http", "*:8080:", "d:\MySite"); >-->> iisManager.Update();I think .Update() method is replaces with .CommitChanges()
  • Anonymous
    September 28, 2007
    More than a year ago I wrote about Microsoft.Web.Administration.dll and how it was a new API we were
  • Anonymous
    October 23, 2007
    The comment has been removed
  • Anonymous
    October 23, 2007
    Yes, you can use it to manage IIS 7 running in Windows Vista SP1 or Windows Server 2008 but only from a client running Windows Vista SP1 or Windows Server 2008. The way to do it is creating a ServerManager like this:ServerManager remoteManager = ServerManager.OpenRemote("yourServer");
  • Anonymous
    October 24, 2007
    More than a year ago I wrote about Microsoft.Web.Administration.dll and how it was a new API we were
  • Anonymous
    October 25, 2007
    Thanks for your reply Carlos.Do you know where I can find some 'good' documentation on this?
  • Anonymous
    October 25, 2007
    Also is there anyway to control FTP settings for a Site?
  • Anonymous
    November 12, 2007
    When using FTP 7.0 with IIS 7.0 and using Microsoft.Web.Administration how do add ftp settings to a web site? Or do I have to manually edit the .config files xml to add it?If not supported, would this feature be supported in future?
  • Anonymous
    November 13, 2007
    You can absolutely use Microsoft.Web.Administration for that, however you will either need to use the loosely typed model (ConfigurationSection, ConfigurationElement, etc) or you will need to create your own strongly typed classes for it.For example if you want to set something in the site, you can use:ConfigurationElement ftpServer =ServerManager.Sites["Default Web Site"].GetChildElement("ftpServer");And then use that for anything you need, also FTP defines several sections as well that you can use GetSection() over a Configuration object.
  • Anonymous
    January 06, 2008
    IIS7伴随着Vista已经悄悄来临,学习的时候我也摘录了一些有关于此的文章。 不敢独享,还是贴出来大家共享吧!
  • Anonymous
    February 14, 2008
    Will this all be exposed to the (VB) scripting engine?
  • Anonymous
    January 08, 2009
    Hi Carlos,How do I query the current memory usage of a Site?Regards,Marcel
  • Anonymous
    March 28, 2009
    Интересную тему для вордпресса поставили. Сами делали или стандартную какую брали? :)
  • Anonymous
    May 20, 2009
    Hi Carlos ,I am facing that create a virtual director from C# code without having admin previliages the code is           System.DirectoryServices.DirectoryEntry oDE;           System.DirectoryServices.DirectoryEntries oDC;           System.DirectoryServices.DirectoryEntry oVirDir;           oVirDir = null;           try           {               // check whether to create FTP or IIS virtual directory               if (IsFTP)               {                   oDE = new DirectoryEntry("IIS://" + deploymentServerName + "/MSFTPSVC/1/Root");               }               else               {                   oDE = new DirectoryEntry("IIS://" + deploymentServerName + "/W3SVC/1/Root");               }               try               {                   string directoryEntryNameStr = oDE.Name;               }now tell me a solution when I can create a virtual directory without being admin to windows Vista.I clicked IIS6.0 metadata and configuration compatibilty and manament from window feature on/off/
  • Anonymous
    May 21, 2009
    For security reasons you cannot add a virtual directory unless you are an administrator.You can imagine that if a non-administrator was able to expose a random directory over the URL namespace of the site would be a bad idea.
  • Anonymous
    May 24, 2009
    本文翻译整理自CarlosAguilarMares的blog文章:Microsoft.Web.AdministrationinIIS7。请注意本文的内容均基于WindowsVista...
  • Anonymous
    May 27, 2009
    Can we use the Microsoft.Web.Administration from a Windows Server 2008 to remotely manage IIS 6 running on Windows Server 2003?  Where is the Microsoft.Web.Administration located?  Is it part of .Net or Windows?
  • Anonymous
    May 27, 2009
    Unfortunately you can only use it to manage a Windows Vista, Windows Server 2008, Windows 7, and Windows Server 2008 R2 server.It is not distributed with .net but instead is part of IIS.
  • Anonymous
    May 27, 2009
    Are they any major changes to the Microsoft.Web.Administration API's in IIS 7.5?
  • Anonymous
    June 16, 2009
    I am using VS2008 on an XP machine and cannot see the Microsoft.Web.Administration namespace. I guess this is because it is part of IIS7, which is not on the development machine. The finished code is to run on an IIS 7 server. I'd like to create a reference but don't know where to find one. Can anyone help please?Thanks!
  • Anonymous
    June 16, 2009
    Update: I installed the IIS Remote Manager on the XP dev machine thinking I might get the dll with it, but it appears not...
  • Anonymous
    July 07, 2009
    The comment has been removed
  • Anonymous
    July 08, 2009
    素人ホストでは日頃のストレスを発散したい、もう一度恋がしたい、そういた女性が癒しを求めて登録されています。当サイトは癒やされたい女性・寂しい女性を癒やす男性が集うカップリングサイトです
  • Anonymous
    July 09, 2009
    The comment has been removed
  • Anonymous
    November 01, 2010
    Just wondering, How would one go about using this API to both View and Modify the contents of the IPGrant and/or Deny Table?Could you be so kind as to give an explanation or hint?
  • Anonymous
    November 01, 2010
    @Philip, here is an example:       using(ServerManager serverManager = new ServerManager()) {           Configuration config = serverManager.GetApplicationHostConfiguration();           ConfigurationSection ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity");           ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection();           ConfigurationElement addElement = ipSecurityCollection.CreateElement("add");           addElement["ipAddress"] = @"169.132.124.234";           ipSecurityCollection.Add(addElement);           serverManager.CommitChanges();       }   }You can also learn more at the configReference where we have samples for all sections: www.iis.net/.../ipSecurity
  • Anonymous
    January 20, 2011
    using (ServerManager mgr = new ServerManager())                   {                       Site site = mgr.Sites[siteName];                       if (site != null)                       {                           Microsoft.Web.Administration.Application app = site.Applications[appName];                           if (app == null)                           {                               Microsoft.Web.Administration.Application iisApplication =                               site.Applications.Add(appName, ApplicationPath);                               //sets the application to Classic .Net AppPool                               iisApplication.ApplicationPoolName = "ASP.NET v4.0 wcf";                               //mgr.ApplicationPools["DefaultAppPool"].Recycle();                           }
  • Anonymous
    March 18, 2011
    The comment has been removed
  • Anonymous
    July 19, 2011
    非常不错,但是最近我在开发一个使用IIS Express运行的控制本地系统自带的IIS的系统,问题出现了。可以获取到站点信息,但是不能获取到Site.State、Stop、Start都不能使用,保异常为:未实现的方法。但是该用VS开发服务器就没有这样的问题,难道是配置问题?不知道是什么原因,请求协助Email:yandavid@163.com.谢谢。
  • Anonymous
    July 20, 2011
    How do I get TARGETSITE (id for the website ) programmetically? Thx For example, get ID for MyWebSite?
  • Anonymous
    August 29, 2011
    Would love to be able to get code to delete 2 virtual directories/applications then check to see if application pool has any other apps assigned to it.  If not, delete the app Pool.
  • Anonymous
    November 24, 2011
    I'm trying to create a virtual directory using C#. When try to add a reference to Microsoft.Web.Administration Namespace I can't find it in the list. Any clue?And thanks for the great article.
  • Anonymous
    August 14, 2012
    How can  I using Microsoft.Web.Administration in my asp.net web site.I want create a web page to manager the iis.
  • Anonymous
    January 08, 2013
    How to assign a specific user credentials for a site in IIS 6.0 using Visual Studio help please
  • Anonymous
    January 13, 2013
    关于ASP.NET操作IIS7的范例,可以查阅www.china-java.net/frmDOCView.aspx
  • Anonymous
    February 27, 2013
    thanks
  • Anonymous
    February 11, 2014
    its not working for remote administration, any code is really appritiated
  • Anonymous
    September 09, 2014
    Error On remote machine?Unauthorized Access Exception
  • Anonymous
    December 08, 2015
    i want a vb code that can query the iis metadata to give the list of site that has browsing directory enabled status .can anyone provide it???
  • Anonymous
    May 18, 2016
    Hi this is great, however I am sitting with a major headache and cannot for the love of me add the node ""to the file ... do you perhaps have a solution? I had tried the below to no avail. Configuration config = serverManager.GetWebConfiguration("Default Web Site"); ConfigurationSection applicationPoolsSection = config.GetSection("system.web"); ConfigurationElementCollection applicationPoolsCollection = applicationPoolsSection.GetCollection(); ConfigurationElement addElement = applicationPoolsCollection.CreateElement("identity"); addElement["key"] = "impersonate"; addElement["value"] = "true"; applicationPoolsCollection.Add(addElement); serverManager.CommitChanges();
    • Anonymous
      June 06, 2016
      You need to make sure request the right section, in this case it is system.web/identity (the whole thing), you can figure that out looking into %windir%\system32\inetsrv\config\schemaSo do: using(ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetWebConfiguration("Your Site"); ConfigurationSection identitySection = config.GetSection("system.web/identity"); identitySection["impersonate"] = true; serverManager.CommitChanges(); }