简体   繁体   中英

How to create an HTTP redirect from a virtual directory using C#

I can create an http redirect in my IIS by using the following code. However, it only creates a redirect for the main site "MySite" itself. How do I programatically add a redirect to a virtual directory? Is there some setting I need to set when I create the VD? Thanks!

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();

If your hosting it in IIS 7+ then you could use web.config .

Place a web.config in the directory and then add

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

You can read up on the properties here

Sean,

What your code is doing is essentially modifying the web.config file for your site. The virtual directory is likely configured as an application so it would have its own web.config file. Did you try doing the same thing but simply changing:

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

Also, the virtual directory, since it is a child application may already be inheriting the httpRedirect setting from the parent site, I'd check first that this is not the case.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM