C# .Net核心和Microsoft.Web.Administration
我正在尝试编写一个可以在远程srver上向IIS添加绑定的服务。我正在使用Microsoft.Web.Administration。 我添加绑定的代码如下所示:C# .Net核心和Microsoft.Web.Administration,c#,.net,ssl,iis,C#,.net,Ssl,Iis,我正在尝试编写一个可以在远程srver上向IIS添加绑定的服务。我正在使用Microsoft.Web.Administration。 我添加绑定的代码如下所示: public static bool AddSiteBinding(string siteName, string ipAddress, string tcpPort, string hostHeader, string protocol) { try { if (
public static bool AddSiteBinding(string siteName, string ipAddress, string tcpPort, string hostHeader, string protocol)
{
try
{
if (string.IsNullOrEmpty(siteName))
{
throw new ArgumentNullException("siteName", "AddSiteBinding: siteName is null or empty.");
}
//get the server manager instance
using (ServerManager mgr = ServerManager.OpenRemote(@"\\Qasql01\c$\Windows\System32\inetsrv\config\applicationHost.config"))
//using (ServerManager mgr = new ServerManager())
{
SiteCollection sites = mgr.Sites;
Site site = mgr.Sites[siteName];
if (site != null)
{
string bind = ipAddress + ":" + tcpPort + ":" + hostHeader;
//check the binding exists or not
foreach (Binding b in site.Bindings)
{
if (b.Protocol == protocol && b.BindingInformation == bind)
{
throw new Exception("A binding with the same ip, port and host header already exists.");
}
}
Binding newBinding = site.Bindings.CreateElement();
newBinding.Protocol = protocol;
newBinding.BindingInformation = bind;
site.Bindings.Add(newBinding);
mgr.CommitChanges();
return true;
}
else
throw new Exception("Site: " + siteName + " does not exist.");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
问题是,此代码(在本地工作正常)在对象引用未设置为对象实例时崩溃。在远程服务器上运行时出错。本例中的远程服务器是Windows server 2012上的IIS 8.5。我已经尝试了所有我能找到的解决办法,但一点运气都没有。我正在以管理员身份运行VS2017中的代码。以下是我尝试过的:
好的,我刚刚想好了。首先,我确信OpenRemote不起作用。我读的文章展示了OpenRemote在配置文件中传递的示例——这是不对的。在对MS代码进行深入研究后,我发现有一个构造函数接受applicationHost.config路径,但没有一个OpenRemote版本接受配置路径。这可能在IIS7和MWA的早期版本中起作用,但肯定不是这个版本。当然,传入服务器或IP也不起作用。我将实例化ServerManager的行更改为:
using (ServerManager mgr = new ServerManager(@"\\qasql01\IISSharedConfig\applicationHost.config"))
现在它开始工作了。这似乎是配置远程服务器的唯一方法。至少通过这种方式,您可以使用普通ole文件安全性,并绕过所有DCOM神秘的安全要求。我可以确认,用户2033791给出的答案非常有效(IIS8.5/2012R2)。远程IIS系统会自动拾取额外的绑定,其他应用程序不会被回收 使用的构造函数使用
[Browsable(false)]
属性隐藏,并且根据MSDN,该构造函数仅供Microsoft内部使用。所以买家要小心;-)
参考资料:
据我所知,这意味着使用服务器名,而不是applicationHost.config的路径。也许这就是问题所在
当我升级Microsoft.Web.Administration NuGet软件包时,它停止工作。当我降级回7.0.0.0版时工作正常。哪个MWA?无法使用NuGet版本。哪一行出现空引用异常?@virustorm在实例化
mgr
的using语句后直接插入该行。当然,您不能访问mgr.Sites
,因为mgr为null,所以永远不会创建它@Lex Li我使用的是NuGet版本,根据微软的说法,该版本与.Net core兼容。2016年10月,微软接管了MWA,并将其作为正式的NuGet软件包。因此,它现在由Microsoft拥有和维护。Microsoft出于完全不同的目的(IIS REST API)接管了NuGet软件包,因此您仍然不应该以这种方式使用它,这应该是对另一个答案的评论,而不是答案,因为您自己没有提供答案,但在现有答案的基础上,我确实想发表评论,但除了直接回复外,我不允许发表评论,我的投票结果也不可见。因为很少有人使用这个库,所以我想确保每个人都知道给定的答案是有效的,并提供额外的相关细节。您可以查看我在user2033791的答案下留下的评论。这种方法是错误的。它仍然是错误的方法。您可以使用ServerManager
解析配置文件并修改一些设置,但如果不使用DCOM接口,您的所有更改都会留在该文件上,并且可能会中断某些MWA功能(例如站点启动/停止),因为该构造函数是为本地配置文件设计的。