如何使用C#从虚拟目录创建HTTP重定向

时间:2011-06-02 20:02:20

标签: c# iis redirect directory virtual

我可以使用以下代码在IIS中创建http重定向。但是,它只为主站点“MySite”本身创建重定向。如何以编程方式将重定向添加到虚拟目录?在创建VD时是否需要设置一些设置?谢谢!

ServerManager iisManager = new ServerManager();
Configuration config = iisManager.GetWebConfiguration("MySite");
ConfigurationSection httpRedirectSection =  config.GetSection("system.webServer/httpRedirect");
httpRedirectSection["enabled"] = true;
httpRedirectSection["destination"] = @"http://www.google.com";
httpRedirectSection["exactDestination"] = false;
httpRedirectSection["httpResponseStatus"] = @"Found";

iisManager.CommitChanges();

2 个答案:

答案 0 :(得分:0)

肖恩,

您的代码正在做的主要是修改您网站的web.config文件。虚拟目录可能配置为应用程序,因此它将拥有自己的web.config文件。你尝试做同样的事情,只是改变:

Configuration config = iisManager.GetWebConfiguration("MySite/VirtDirName");

此外,虚拟目录,因为它是子应用程序可能已经从父站点继承了httpRedirect设置,我首先检查不是这种情况。

http://www.iis.net/ConfigReference/system.webServer/httpRedirect

http://msdn.microsoft.com/en-us/library/ms178685.aspx

答案 1 :(得分:0)

如果您在IIS 7+中托管它,那么您可以使用web.config

在目录中放置web.config,然后添加

<?xml version="1.0"?>
<configuration>
  <system.webServer>
    <httpRedirect enabled="true" destination="/[PathFromRoot]/" childOnly="true" httpResponseStatus="Temporary" />
  </system.webServer>
</configuration>

您可以阅读属性here