使用 IHttpHandler 进行域名转发






3.50/5 (10投票s)
2003 年 3 月 12 日
1分钟阅读

156806

897
使用 HttpHandlers 根据请求的主机名(域名)将用户转发到不同的网页。
引言
在本文中,我将介绍如何使用自定义 HttpHandler
作为域名转发器。
背景
借助 IIS 中的 Hostheader 功能,您可以将多个主机名映射到单个 IP 地址。例如,您的 IIS 服务器具有 IP 地址 195.243.118.165。您或您的 ISP 为此 IP 地址拥有一些 A 记录。
www.mydomain.com | A | 195.243.118.165 |
www.virtualdomain1.com | A | 195.243.118.165 |
www.virtualdomain2.com | A | 195.243.118.165 |
现在,您已在 IIS 中配置了一个网站,该网站响应所有这些域名。下图显示了一个示例 IIS 配置。
所有对 www.mydomain.com、www.virtualdomain1.com 和 www.virtualdomain2.com 的请求都指向同一个网站。通常,您需要进行这样的配置,因为公共 IP 地址的数量有限。
此时,您希望根据用户使用的域名提供不同的网页。此示例应用程序将为此问题提供一个简单的解决方案。
使用代码
在您的 ASP.NET 应用程序中创建一个实现 IHttpHandler
的类。您需要实现一种方法和一个属性
public void ProcessRequest (HttpContext)
public void IsReusable
以下是示例代码
public class DomainHandler : IHttpHandler
{
/// Implementing IHttpHandler
public void ProcessRequest(HttpContext context)
{
// Extract the host name from the request url
// an look up the redirect url in the Web.config
String redir = ConfigurationSettings.AppSettings
[context.Request.Url.Host];
if (redir != null)
{
// check for valid redirect url, preventing loops
if (RedirectIsValid(redir, context.Request.Url))
{
// redirect the user to the url found in web.config
context.Response.Redirect(redir, true);
}
else
{
// display an error.
context.Response.Write("<h1><font
color=red>Error invalid DomainHandler
configuration</font></h1><br>
<b>Please check your Web.config
file.</b>");
}
}
}
// prevents possible redirect loops
// it is not allowed to have an redirect url targeting its self
private bool RedirectIsValid(String redir, Uri currentUri)
{
String val1 = redir.ToLower();
String url = currentUri.AbsoluteUri.ToLower();
String host = currentUri.Host.ToLower();
if (val1 == url) { return false; }
if (val1 == ( "http://" + host)) { return false; }
if (val1 == ("http://" + host + "/")) { return false; }
if (val1 == host) { return false; }
if (val1 == (host + "/")) { return false; }
return true;
}
/// Implementing IHttpHandler
public bool IsReusable
{
get
{
return true;
}
}
}
//
关注点
我决定将我的 URL 映射存储在 web.config 文件中,作为 appSettings
部分中的键值对。此外,您还必须在 web.config 文件中注册新的 HttpHandler
。
此处提供了示例 web.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!--
Use as keys your full qualified host names.
As Value you provide a absolute url, you want to redirect to.
-->
<add key="localhost" value="https:///DomainForward/target1.htm" />
<add key="www.virualdomain1.com" value="http://www.myDomain.com/domain1" />
<add key="www.virualdomain2.com" value="http://www.myDomain.com/domain2" />
</appSettings>
<system.web>
<compilation
defaultLanguage="c#"
debug="true"
/>
<httpHandlers>
<add verb="*" path="Default.aspx"
type="DomainFilter.DomainHandler, DomainFilter" />
</httpHandlers>
</system.web>
</configuration>
在 httpHandlers
部分的 path
属性中,您指定一个与“IIS 默认页面配置”匹配的实际现有文件名。
在我的示例应用程序中,为了简单起见,我使用了子网站,这是 Visual Studio 中的默认设置。在实际应用中,您会将应用程序安装在根网站中。