簡體   English   中英

使用 C# 以編程方式在 IIS 中創建網站並設置端口號

[英]Programmatically create a web site in IIS using C# and set port number

我們已經能夠創建一個網站。 我們使用此鏈接中的信息做到了這一點:

https://msdn.microsoft.com/en-us/library/ms525598.aspx

但是,我們想使用除端口 80 之外的端口號。我們如何做到這一點?

我們正在使用 IIS 6

如果您使用的是IIS 7,則有一個名為Microsoft.Web.Administration的新托管API。

以上博客文章中的示例:

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

如果您使用的是IIS 6並希望這樣做,那么不幸的是,它會更復雜。

您將必須在每台服務器上創建一個Web服務,一個處理網站創建的Web服務,因為通過網絡進行的直接用戶模擬無法正常工作(如果我沒有記錯的話)。

您將必須使用Interop Services並執行類似的操作(此示例使用兩個對象,服務器和站點,它們是存儲服務器和站點的配置的自定義類的實例):

string metabasePath = "IIS://" + server.ComputerName + "/W3SVC";
DirectoryEntry w3svc = new DirectoryEntry(metabasePath, server.Username, server.Password);

string serverBindings = ":80:" + site.HostName;
string homeDirectory = server.WWWRootPath + "\\" + site.FolderName;


object[] newSite = new object[] { site.Name, new object[] { serverBindings }, homeDirectory };

object websiteId = (object)w3svc.Invoke("CreateNewSite", newSite);

// Returns the Website ID from the Metabase
int id = (int)websiteId;

在這里查看更多

這是解決方案。
博客文章:如何在IIS 7中添加新網站

在按鈕上單擊:

try
 {
  ServerManager serverMgr = new ServerManager();
  string strWebsitename = txtwebsitename.Text; // abc
  string strApplicationPool = "DefaultAppPool";  // set your deafultpool :4.0 in IIS
  string strhostname = txthostname.Text; //abc.com
  string stripaddress = txtipaddress.Text;// ip address
  string bindinginfo = stripaddress + ":80:" + strhostname;

  //check if website name already exists in IIS
    Boolean bWebsite = IsWebsiteExists(strWebsitename);
    if (!bWebsite)
     {
        Site mySite = serverMgr.Sites.Add(strWebsitename.ToString(), "http", bindinginfo, "C:\\inetpub\\wwwroot\\yourWebsite");
        mySite.ApplicationDefaults.ApplicationPoolName = strApplicationPool;
        mySite.TraceFailedRequestsLogging.Enabled = true;
        mySite.TraceFailedRequestsLogging.Directory = "C:\\inetpub\\customfolder\\site";
        serverMgr.CommitChanges();
        lblmsg.Text = "New website  " + strWebsitename + " added sucessfully";
     }
     else
     {
        lblmsg.Text = "Name should be unique, " + strWebsitename + "  is already exists. ";
     }
   }
  catch (Exception ae)
  {
      Response.Redirect(ae.Message);
   }

遍歷站點是否名稱已存在

    public bool IsWebsiteExists(string strWebsitename)
    {
        Boolean flagset = false;
        SiteCollection sitecollection = serverMgr.Sites;
        foreach (Site site in sitecollection)
        {
            if (site.Name == strWebsitename.ToString())
            {
                flagset = true;
                break;
            }
            else
            {
                flagset = false;
            }
        }
        return flagset;
    }

嘗試使用以下代碼來了解未使用的端口號

        DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");

        // Find unused ID PortNo for new web site
        bool found_valid_port_no = false;
        int random_port_no = 1;

        do
        {
            bool regenerate_port_no = false;
            System.Random random_generator = new Random();
            random_port_no = random_generator.Next(9000,15000);

            foreach (DirectoryEntry e in root.Children)
            {
                if (e.SchemaClassName == "IIsWebServer")
                {

                    int site_id = Convert.ToInt32(e.Name);
                    //For each detected ID find the port Number 

                     DirectoryEntry vRoot = new DirectoryEntry("IIS://localhost/W3SVC/" + site_id);
                     PropertyValueCollection pvcServerBindings = vRoot.Properties["serverbindings"];
                     String bindings = pvcServerBindings.Value.ToString().Replace(":", "");
                     int port_no = Convert.ToInt32(bindings);

                     if (port_no == random_port_no)
                    {
                        regenerate_port_no = true;
                        break;
                    }
                }
            }

            found_valid_port_no = !regenerate_port_no;
        } while (!found_valid_port_no);

        int newportId = random_port_no;

我雖然在這里回答了所有問題,但也進行了測試。 這是此問題答案的最簡潔的版本。 但是,這仍然無法在IIS 6.0上運行。 因此需要IIS 8.0或更高版本。

string domainName = "";
string appPoolName = "";
string webFiles = "C:\\Users\\John\\Desktop\\New Folder";
if (IsWebsiteExists(domainName) == false)
{
    ServerManager iisManager = new ServerManager();
    iisManager.Sites.Add(domainName, "http", "*:8080:", webFiles);
    iisManager.ApplicationDefaults.ApplicationPoolName = appPoolName;
    iisManager.CommitChanges();
}
else
{
    Console.WriteLine("Name Exists already"); 
}


public static bool IsWebsiteExists(string strWebsitename)
{
    ServerManager serverMgr = new ServerManager();
    Boolean flagset = false;
    SiteCollection sitecollection = serverMgr.Sites;
    flagset = sitecollection.Any(x => x.Name == strWebsitename);
    return flagset;
}
  1. 在站點的屬性中,選擇“網站”選項卡,然后指定“ TCP端口”。
  2. 在Studio中以調試目的指定http:// localhost:<port> / <site&gt ; 在“使用本地IIS Web服務器”的“ Web”選項卡上

這種簡化的方法將創建一個具有默認綁定設置的站點,並在需要時創建應用程序池:

public void addIISApplication(string siteName, string physicalPath, int port, string appPoolName)
{
    using (var serverMgr = new ServerManager())
    {
        var sitecollection = serverMgr.Sites;
        if (!sitecollection.Any(x => x.Name.ToLower() == siteName.ToLower()))
        {
            var appPools = serverMgr.ApplicationPools;
            if (!appPools.Any(x => x.Name.ToLower() == appPoolName.ToLower()))
            {
               serverMgr.ApplicationPools.Add(appPoolName);
            }

            var mySite = serverMgr.Sites.Add(siteName, physicalPath, port);
            mySite.ApplicationDefaults.ApplicationPoolName = appPoolName;
            serverMgr.CommitChanges();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM