使用C#在IIS中以编程方式创建网站并设置端口号

6ss1mwsb  于 2023-03-12  发布在  C#
关注(0)|答案(6)|浏览(214)

我们已经能够创建网站。我们使用此链接中的信息完成此操作:
https://msdn.microsoft.com/en-us/library/ms525598.aspx
但是,我们希望使用端口80以外的端口号。如何操作?
我们正在使用IIS 6

mo49yndu

mo49yndu1#

如果您使用的是IIS 7,则有一个名为Microsoft.Web.Administration的新托管API
上面的博客文章中有一个例子:

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

如果您使用的是IIS6并希望执行此操作,那么不幸的是,它会更加复杂。
您必须在每台服务器上创建一个Web服务,一个处理网站创建的Web服务,因为通过网络直接模拟用户将无法正常工作(如果我没有记错的话)。
您必须使用互操作服务并执行与此类似的操作(此示例使用两个对象server和site,它们是存储服务器和站点配置的自定义类的示例):

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;

查看更多here

nnsrf1az

nnsrf1az2#

这就是解决办法。
Blog article : How to add new website in 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;
    }
ghg1uchk

ghg1uchk3#

尝试以下代码以了解未使用的端口号

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;
n3h0vuf2

n3h0vuf24#

我已经通过了所有的答案在这里,也测试。这里是最干净的聪明版本的答案这个问题。然而,这仍然不能工作在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;
}
btxsgosb

btxsgosb5#

此简化方法将使用默认绑定设置创建站点,如果需要,还将创建应用程序池:

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();
        }
    }
}
wztqucjr

wztqucjr6#

1.在站点属性中选择“网站”选项卡并指定TCP端口。
1.在工作室调试目的指定;在“使用本地IIS Web服务器”的Web选项卡上

相关问题