C# 获取我的 Web 应用程序的基本 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15925036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:28:56  来源:igfitidea点击:

Get Base URL of My Web Application

c#iis-7

提问by Joe.Net

Is it possible to get the base URL of IIS 7 by using Microsoft.Web.Administration.ServerManager?

是否可以使用 获取 IIS 7 的基本 URL Microsoft.Web.Administration.ServerManager

Typically this would be:

通常这将是:

http://localhost

but I need to get it programmatically.

但我需要以编程方式获取它。

If I can't use ServerManagerwhat is the best alternative?

如果我不能使用ServerManager什么是最好的选择?

采纳答案by A J

You can use string baseURL = HttpContext.Current.Request.Url.Host.

您可以使用string baseURL = HttpContext.Current.Request.Url.Host.

回答by Munir Husseini

For those interested in the usage of Microsoft.Web.Administration.ServerManager, here's some code. Consider that an IIS application my have more than one binding, resulting in more than one URL per web application.

对于那些对 Microsoft.Web.Administration.ServerManager 的用法感兴趣的人,这里有一些代码。考虑到 IIS 应用程序可能有多个绑定,导致每个 Web 应用程序有多个 URL。

var siteName = "Default Web Site";
var appPath = "MyWebApplication";

var serverManager = new ServerManager();
var site = serverManager.Sites[siteName];
appPath = appPath.StartsWith("/") ? appPath : "/" + appPath;
var app = site.Applications[appPath];

var urls = new List<string>();

foreach (var binding in site.Bindings)
{
    var sb = new StringBuilder();
    sb.Append(binding.Protocol);
    sb.Append("://");
    if (!string.IsNullOrWhiteSpace(binding.Host))
    {
        sb.Append(binding.Host);
    }
    else
    {
        if (Equals(binding.EndPoint.Address, IPAddress.Any))
        {
            sb.Append("localhost");
        }
        else
        {
            sb.Append(binding.EndPoint.Address);
        }
    }

    if (binding.EndPoint.Port != 80)
    {
        sb.Append(":");
        sb.Append(binding.EndPoint.Port);
    }

    sb.Append(app.Path);
    urls.Add(sb.ToString());
}