我想知道如何在运行时使用 ASP.NET 获取当前站点的 IIS 绑定(bind)设置(主机名、端口、IP 地址)。
.NET 是否提供任何方式来获取这些信息?
编辑:我需要一种方法来配置 http 和 https 端口,以便在从 http 切换到 https 时重定向到正确的端口,如果使用其他端口,则从 https 回到 http,然后使用 80/443。有没有办法在没有扩展权限的情况下做到这一点?
问候
最佳答案
您可以使用以下代码来获取绑定(bind):
public static IEnumerable<Binding> GetSiteBindings(Site site)
{
BindingCollection bindings = site.Bindings;
if (bindings != null)
{
foreach (Binding binding in bindings)
{
if (binding != null)
{
yield return binding;
}
}
}
yield return null;
}
以下代码可用于测试上述方法:
ServerManager mgr = new ServerManager();
foreach (Site s in mgr.Sites)
{
Response.Write("Site: " + s);
Response.Write("<br/>");
var siteBindings = GetSiteBindings(s);
if (siteBindings != null)
{
foreach (var binding in siteBindings)
{
if (binding != null)
{
var bindingInformation = binding.BindingInformation;
var host = binding.Host;
var endPoint = binding.EndPoint;
Response.Write("Host: " + host + ", BindingInfo: " + bindingInformation + ", EndPoint: " + endPoint);
Response.Write("<br/>");
}
}
}
Response.Write("----------------------------------");
Response.Write("<br/>");
}
使用的命名空间:
<%@ Import Namespace="System.Diagnostics" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="Microsoft.Web.Administration" %>
程序集引用:Microsoft.Web.Administration
将上述代码放入 Sample.aspx 中进行测试:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Diagnostics" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="Microsoft.Web.Administration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
ServerManager mgr = new ServerManager();
foreach (Site s in mgr.Sites)
{
Response.Write("Site: " + s);
Response.Write("<br/>");
var siteBindings = GetSiteBindings(s);
if (siteBindings != null)
{
foreach (var binding in siteBindings)
{
if (binding != null)
{
var bindingInformation = binding.BindingInformation;
var host = binding.Host;
var endPoint = binding.EndPoint;
Response.Write("Host: " + host + ", BindingInfo: " + bindingInformation + ", EndPoint: " + endPoint);
Response.Write("<br/>");
}
}
}
Response.Write("----------------------------------");
Response.Write("<br/>");
}
}
public static IEnumerable<Binding> GetSiteBindings(Site site)
{
BindingCollection bindings = site.Bindings;
if (bindings != null)
{
foreach (Binding binding in bindings)
{
if (binding != null)
{
yield return binding;
}
}
}
yield return null;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="HtmlForm" runat="server">
<div>
</div>
</form>
</body>
</html>
会给你这样的输出:
关于asp.net - 在运行时获取 IIS 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4763710/