Asp. NET adds virtual directories and host headers through WMI creation site

Source: Internet
Author: User
Tags add format auth header connect net string tostring
Preface This article describes how ASP.net creates a site, adds a virtual directory, and adds a host header through WMI. and has been tested in Windows Server 2003 and IIS6 environments.

This thing took Lao Tze 3 days to finish, spent a few hours to write code, and also spent a lot of time to solve the problem of Win32:access denied error. Of course, I would like to point out that you do not set too large a permission for either the network server account or the iusr_<servername> account. I know nothing about the security mechanisms of WMI and IIS metabase. I'm just solving the problem.

Look at the code

To get the site identifier first from Internet Information Services (IIS) Manager, click on the "Site" root node and the right "identifier" displays the ID of the site. The identifier for the default Web site is usually 1.

To get the function of the website identification, we need to use a namespace, the code is as follows:

Using System.Management;

All of the following ' ServerName ' indicate your server name, or if your code is running locally, you can also use a point.

To create a site, you will use the following functions. This function returns the ID of the new Web site so that you can further manipulate the site.

public static string Createwebsite (String serverName, String apppoolname, String ip,string pathtoroot, string hostName, S
    Tring DomainName, int port) {connectionoptions options = new ConnectionOptions (); Options.
    authentication = Authenticationlevel.connect; Options.
    Enableprivileges = true; Options.
    impersonation = ImpersonationLevel.Impersonate; Managementscope scope = new Managementscope (string.
    Format (@\\{0}\root\microsoftiisv2, ServerName), options); Scope.
    Connect ();

    ManagementObject ow3svc = new ManagementObject (scope, new Managementpath (@ "iiswebservice= ' w3svc '"), null);
    managementbaseobject[] ServerBindings = new Managementbaseobject[1]; Serverbindings[0] = createserverbinding (scope, String. Format ("{0}.{
    1} ", HostName, domainname), IP, port);
    Managementbaseobject InputParameters = ow3svc.getmethodparameters ("CreateNewSite"); inputparameters["ServerComment"] = string. Format ("{0}.{ 1} ", HostName, domainname);
    inputparameters["serverbindings"] = ServerBindings;
    inputparameters["Pathofrootvirtualdir"] = Pathtoroot;

    Managementbaseobject Outparameter = Ow3svc.invokemethod ("CreateNewSite", inputparameters, NULL); String siteId = Convert.ToString (outparameter.properties["returnvalue"). Value). Replace ("Iiswebserver= ' w3svc/", "").
    Replace ("'", ""); ManagementObject owebvirtdir = new ManagementObject (scope, new Managementpath (string.
    Format (@ "iiswebvirtualdirsetting.name= ' w3svc/{0}/root '", siteId)), null); owebvirtdir.properties["AppFriendlyName"]. Value = string. Format ("{0}.{
    1} ", HostName, DomainName); owebvirtdir.properties["AccessRead"].
    Value = true; owebvirtdir.properties["AuthFlags"]. Value = 5;
    Integrated Windows Auth. owebvirtdir.properties["AccessScript"].
    Value = true; owebvirtdir.properties["AuthAnonymous"].
    Value = true; owebvirtdir.properties["AppPoolId"].
    Value = AppPoolName;Owebvirtdir.put (); ManagementObject site = new ManagementObject (scope, New Managementpath (Convert.ToString (Outparameter.properti es["ReturnValue"].
    Value)), null); Site.
    InvokeMethod ("Start", null);
return siteId; }

Create a virtual directory:

public static void Addvirtualfolder (String serverName, String websiteid,string name, string path) {Managementscope s Cope = new Managementscope (string.
    Format (@ "\\{0}\root\microsoftiisv2", ServerName)); Scope.

    Connect (); String siteName = String.

    Format ("W3svc/{0}/root/{1}", WebSiteID, name);
    ManagementClass mc = new ManagementClass (scope,new managementpath ("iiswebvirtualdirsetting"), null); ManagementObject Owebvirtdir = MC.

    CreateInstance (); owebvirtdir.properties["Name"].
    Value = SiteName; owebvirtdir.properties["Path"].
    Value = path; owebvirtdir.properties["AuthFlags"]. Value = 5;
    Integrated Windows Auth. owebvirtdir.properties["EnableDefaultDoc"].
    Value = true;
    Date, time, size, extension, longdate; owebvirtdir.properties["DirBrowseFlags"].
    Value = 0x4000003e; owebvirtdir.properties["AccessFlags"]. Value = 513;

    Read Script owebvirtdir.put (); ManagementObject mo = new ManagementObject (scope, new System.Management.MaNagementpath ("iiswebvirtualdir= '" + SiteName + ""), null); Managementbaseobject inputparameters = mo.
    Getmethodparameters ("AppCreate2");
    inputparameters["AppMode"] = 2; Mo.
    InvokeMethod ("AppCreate2", inputparameters, NULL);  Mo = new ManagementObject (scope, new System.Management.ManagementPath ("iiswebvirtualdirsetting=" + siteName
    + "'"), null); Mo. properties["AppFriendlyName"].
    Value = name; Mo.
Put (); }

Add a host header to a Web site:

 public static void Addhostheader (String serverName, String hostheader, string ip, int port, string we Bsiteid) {Managementscope scope = new Managementscope (string.
    Format (@ "\\{0}\root\microsoftiisv2", ServerName)); Scope.

    Connect (); String siteName = String.

    Format ("' W3svc/{0} '", WebSiteID); ManagementObject mo = new ManagementObject (scope, new System.Management.ManagementPath ("iiswebserversetting=" + site
    Name), NULL); Managementbaseobject[] Websitebindings = (managementbaseobject[]) mo. properties["ServerBindings"].

    Value;

    ManagementObject MCO = createserverbinding (scope, Hostheader, IP, port);
    managementbaseobject[] newwebsitebindings = new managementbaseobject[websitebindings.length+1];
    Websitebindings.copyto (newwebsitebindings, 0);

    Newwebsitebindings[newwebsitebindings.length-1] = MCO; Mo. properties["ServerBindings"].

    Value = newwebsitebindings; Mo.
Put (); }

Finally, don't forget this function, which can bind a network identity to a Web site.

private static ManagementObject createserverbinding (Managementscope scope,string hostName, string ip, int port)
{ C3/>managementclass mc = new ManagementClass (scope,
           new Managementpath ("serverbinding"), null);
    ManagementObject MCO = MC. CreateInstance ();

    Mco. properties["Hostname"]. Value = HostName;
    Mco. properties["IP". Value = IP;
    Mco. properties["Port"]. Value = port;
    Mco. Put ();

    return MCO;
}

Points to note

Safety. If you use the top piece of code does not work. I tried to make it work, but I seemed to overlook 2 things. Access WMI and IIS metabase.

Asp. NET runs on Windows Server 2003 and IIS6.0 is the network Service account that is used by default. However, we still want to use client impersonation.

So add one of the following configurations to the web.config:

<identity impersonate= "true"/>

Using this configuration,iusr_<servername> will use client-side emulation to access IIS metabase. In the following article, I use IUSR_ to represent this account. Don't forget to add your server name to the IUSR_ after the name of the account.

WMI permission settings

    • Control Panel –> Management tools –> Computer Management –> services and applications.
    • Right-click WMI Control and Tap properties.
    • Select the Security tab.
    • Expand Root Tree
    • Click MicrosoftIISv2.
    • Click on "Security settings."
    • Click "Advanced".
    • Double-click IUSR_ (if "group or user name" is not there, add it)
    • "Apply IUSR_" to "this name control and child namespace"
    • "Allow" all permissions.
    • All windows are clicked "OK".

IIS Metabase permission settings

    • Download and install IIS6 Resource Kit.
    • Run metabase Explorer (found in the IIS Resource Kit in the Start menu).
    • Expand the tree directory, right-click the first or second node, and select Permissions.
    • If you are prompted "the current key inherits IT security permissions from the key/", click "Yes".
    • Choose "Iis_iusrs", and if not, add it.
    • Select ' Full Control '.
    • All windows are clicked "OK".

You can run it with enough permissions.

It would be even better if you had an expert who could talk about your feelings about this method and could point out better ways to configure IIS and WMI . I remember before, I have to make up their own, so I do not know whether this method is the best solution.

If you run into any problems when running the code, I'm willing to help.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.