2017-02-09 91 views
1

我想從Windows Server 2012 R2上的IIS獲取網站ID。我想獲取Id,然後在IIS中爲該網站添加一個網站指針。我不確定在哪裏授予代碼工作的權限,同時也不會讓我的web服務器變得脆弱。IIS目錄服務

這裏是我取標識

string result = "-1"; 

    DirectoryEntry w3svc = new DirectoryEntry(string.Format("IIS://{0}/w3svc", "localhost")); 

    foreach (DirectoryEntry site in w3svc.Children) 
    { 
     if (site.Properties["ServerComment"] != null) 
     { 
      if (site.Properties["ServerComment"].Value != null) 
      { 
       if (string.Compare(site.Properties["ServerComment"].Value.ToString(), 

             "website.com", true) == 0) 
       { 
        result = site.Name; 
        break; 

       } 
      } 
     } 
    } 

    return result; 

碼這是拋出的錯誤:

Access is denied. 

Description: An unhandled exception occurred during the execution of the 
current web request. Please review the stack trace for more information 
about the error and where it originated in the code. 


Exception Details: System.Runtime.InteropServices.COMException: Access 
is denied. 


Source Error: 

第22行:的DirectoryEntry W3SVC =新 的DirectoryEntry(的String.format (「IIS:// {0}/w3svc」,serverName)); 第23行: 第24行:的foreach(在w3svc.Children的DirectoryEntry站點) 第25行:{ 第26行:如果(!site.Properties [ 「ServerComment」] = NULL)

Source File: c:\inetpub\wwwroot\DNS_IIS\DNS.aspx.cs Line: 24 

Stack Trace: 


[COMException (0x80070005): Access is denied. 
] 
    System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) 
+597561 
    System.DirectoryServices.DirectoryEntry.Bind() +44 
    System.DirectoryServices.DirectoryEntry.get_IsContainer() +42 
    System.DirectoryServices.DirectoryEntries.GetEnumerator() +49 
    DNS.GetWebSiteId(String serverName, String websiteName) in c:\inetpub 
\wwwroot\DNS_IIS\DNS.aspx.cs:24 
    DNS.btnDNS_Click(Object sender, EventArgs e) in c:\inetpub\wwwroot 
\DNS_IIS\DNS.aspx.cs:85 
    System.Web.UI.WebControls.Button.RaisePostBackEvent(String 
eventArgument) +155 
    System.Web.UI.Page.ProcessRequestMain(Boolean 
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) 
+3804 

回答

1

它是一件很簡單的事情。

因此,我只是將ApplicationPool的標識更改爲LocalSystem,並且它工作得100%。