You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用IIS和C#获取本地网站应用的可访问URL列表?

获取IIS应用的可访问浏览器地址

嘿,我明白你要做什么——搭建一个本地站点来索引所有本地Web应用对吧?你现在的代码已经迈出了第一步,但确实只拿到了应用路径,要凑出完整的可访问URL,得把站点绑定信息和应用路径结合起来才行。

下面是修改后的代码,它能帮你生成每个应用的完整浏览器访问地址:

using System;
using Microsoft.Web.Administration;

namespace IISListerTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var iisManager = new ServerManager();
            SiteCollection sites = iisManager.Sites;

            foreach (Site site in sites)
            {
                // 遍历站点的所有绑定(一个站点可能有多个访问地址)
                foreach (Binding binding in site.Bindings)
                {
                    // 跳过非HTTP/HTTPS的绑定(比如ftp之类的)
                    if (!binding.Protocol.Equals("http", StringComparison.OrdinalIgnoreCase) && 
                        !binding.Protocol.Equals("https", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    // 解析绑定信息:格式通常是 "IP:Port:Hostname"
                    string[] bindingParts = binding.BindingInformation.Split(':');
                    string ip = bindingParts[0];
                    string port = bindingParts[1];
                    string hostname = bindingParts.Length > 2 ? bindingParts[2] : string.Empty;

                    // 处理IP为"*"的情况,本地访问用localhost更方便
                    string accessHost = string.IsNullOrEmpty(hostname) 
                        ? (ip == "*" ? "localhost" : ip) 
                        : hostname;

                    // 拼接基础URL
                    string baseUrl = $"{binding.Protocol}://{accessHost}:{port}";

                    // 遍历站点下的所有应用,拼接完整地址
                    foreach (Application app in site.Applications)
                    {
                        // 处理根应用路径,避免出现双斜杠
                        string fullPath = app.Path == "/" ? string.Empty : app.Path;
                        string fullUrl = $"{baseUrl}{fullPath}";

                        Console.WriteLine($"应用地址: {fullUrl}");
                    }
                }
            }

            // 保持控制台窗口打开,方便查看结果
            Console.WriteLine("\n按任意键退出...");
            Console.ReadKey();
        }
    }
}

关键说明:

  • 绑定信息解析:每个IIS站点的Bindings集合里包含了所有可访问的协议、IP、端口和主机名,我们只需要筛选出HTTP/HTTPS的绑定。
  • 本地访问适配:当绑定IP是*(代表所有IP)时,用localhost作为访问主机更符合本地使用场景;如果有绑定主机名(比如自定义的本地域名),就用那个主机名。
  • 路径拼接处理:根应用的路径是/,直接拼接会出现http://localhost:80//这种错误格式,所以要做个判断去掉多余的斜杠。

这样运行代码后,你就能得到每个应用直接可以在浏览器打开的完整地址了,正好能用到你搭建的本地索引站点里~

内容的提问来源于stack exchange,提问作者Cryptex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:17:52