如何使用C#在IIS中获取网站的“浏览”URL?

时间:2013-11-08 08:07:23

标签: c# asp.net iis iis-7

说,我在IIS中有“站点名称”网站。我可以通过C#代码中的ServerManager类访问其大部分功能。我似乎无法弄清楚如何获取它的“浏览”URL,就像我在下面的屏幕截图中显示的那样?

enter image description here

如果我去管理网站 - >在 IIS管理器中浏览,它将使用URL启动IE:

http://localhost:8080/app1/Default.aspx

所以我需要获得这样的网址。

PS。请注意,我不需要自己启动网站。

4 个答案:

答案 0 :(得分:0)

右键点击并转到edit bindings...下的Host Name,您实际上可以看到它是哪个域。

点击网站,然后点击右侧的操作标签,您可以点击bindings...

获取网址:

HttpContext.Current.Request.Url.AbsoluteUri;
//http://localhost:8080/app1/Default.aspx

HttpContext.Current.Request.Url.AbsolutePath;
// /YourSite/app1/Defaul.aspx

HttpContext.Current.Request.Url.Host;
// localhost:8080

修改

要获取网站信息,请尝试使用HostingEnvironment.ApplicationHost.GetSiteName()HostingEnvironment.ApplicationHost.GetSiteID(),请参阅以下示例(未经过测试):

using (ServerManager sm = new ServerManager())
{
    foreach (Binding b in sm.Sites[HostingEnvironment.ApplicationHost.GetSiteName()].Bindings)
    {
        // ...
    }     
}

答案 1 :(得分:0)

试试这个:

using (Microsoft.Web.Administration.ServerManager sm = Microsoft.Web.Administration.ServerManager.OpenRemote("localhost"))
{
    int counter = 0;
    string[] ipAddress = new string[10];
    string[] sites = new string[10];
    List<Tuple<string, string>> mylist = new List<Tuple<string, string>>();

    foreach (var site in sm.Sites)
    {
        sites[counter] = site.Name;

        foreach(var bnd in site.Bindings)
            ipAddress[counter] = bnd.EndPoint != null ? 
                bnd.EndPoint.Address.ToString() : String.Empty;

        mylist.Add(Tuple.Create(sites[counter], ipAddress[counter]));
                counter++;                    
    }
}

答案 2 :(得分:0)

这是获取浏览网址的一种方式

ServerManager serverMgr = new ServerManager();
Site site = serverMgr.Sites["YourSiteName"];
List<string[]> urls = new List<string[]>();
foreach (Binding binding in site.Bindings)
{
    string bindingInfo = binding.BindingInformation;
    string subString = bindingInfo.Substring(2, bindingInfo.Length - 2);
    string[] adrs = subString.Split(':');
    adrs[0] = "localhost:" + adrs[0];
    urls.Add(adrs);
}

答案 3 :(得分:0)

JexusManager现在是开源的,所以你可以查看它的Binding.ToUri方法的实现,

https://github.com/jexuswebserver/Microsoft.Web.Administration/blob/master/Microsoft.Web.Administration/Binding.cs

        internal string ToUri()
        {
            var address = EndPoint.Address.Equals(IPAddress.Any)
                ? Parent.Parent.Parent.Parent.HostName.ExtractName()
                : EndPoint.AddressFamily == AddressFamily.InterNetwork
                    ? EndPoint.Address.ToString()
                    : string.Format("[{0}]", EndPoint.Address);
            return IsDefaultPort
                ? string.Format("{0}://{1}", Protocol, address)
                : string.Format("{0}://{1}:{2}", Protocol, address, EndPoint.Port);
        }

由于Microsoft的MWA不公开HostName部分,您必须用等效的东西替换它(因为您是初始化ServerManager的人,您应该知道什么是主机名。)