65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 HttpModules 和 URL 重写来处理伪目录请求

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.47/5 (16投票s)

2014年10月30日

CPOL

1分钟阅读

viewsIcon

97856

downloadIcon

10

解释了如何结合使用 HttpModule 和 IIS 来处理伪目录的请求。

引言

当使用 HttpModules 重写 URL 时,访问目录将不起作用。 例如,对 http://somewebsite/fakedirectory/ 的请求将不起作用,除非 fakedirectory 实际存在并且其中包含一些默认索引文件。 发生这种情况是因为当请求进入 IIS 时,它首先确定目录和文件是否实际存在,然后才在您的 ASP.NET 应用程序中实例化 HttpModule。

httpmoduledirectoryhandle/pic1.png

解决方案

解决这个问题实际上非常容易。 首先要做的是加载 IIS 并将 404 错误更改为 URL 目标并将其指向您的站点。

Screenshot - pic2.png

这将告诉 IIS 自动将任何未知请求(例如,到不存在的目录的请求)重定向到您的应用程序。 这样做后,您的应用程序将收到如下请求:http://somewebsite/default.aspx?404;http://somewebsite/fakedirectory/

Using the Code

因为这是标准形式,所以 HttpModule 可以轻松解析它,提取用户想要的真实网站,然后执行标准重写。

internal static String GetRequestedURL(String originalRequest)
{
    // Determine the page the user is requesting.
    String url = originalRequest;
 
    // Check for an error URL which IIS will throw when a non-existing 
    // directory is requested and custom errors are thrown back to this site
    if (url.Contains(";") && url.Contains("404"))
    {
        // Split the URL on the semi-colon. Error requests look like:
        // errorpage.aspx?404;http://originalrequest OR
        // errorpage.aspx?404;http://originalrequest:80
        String[] splitUrl = url.Split(';');
 
        // Set the URL to the original request to allow processing of it.
        if (splitUrl.Length >= 1)
        {
            url = splitUrl[1];
 
            // Remove the first http://
            url = url.Replace("http://", "");
 
            // Get only the application path and beyond of the string. This 
            // may be / if it's in the root folder.
            int index = url.IndexOf(
                System.Web.HttpContext.Current.Request.ApplicationPath);
            if (index >= 0)
            {
                url = url.Substring(index);
            }
        }
    }
 
    return url;
}

GetRequestURL 函数将采用 RawURL 参数,然后检查它是否为 404 错误。 如果是,它将解析出原始请求并返回它。 如果不是 404 错误,那么它将返回未触及的 RawURL。

结论

虽然这是一个相当简单的答案,但我一直在到处寻找解决方案,但似乎没有人有一个简单的答案。 即使使用 HttpHandler 也无法解决问题,因为目录请求上没有扩展名。 这是我发现的最好的解决方案,并且每次都有效,无需进行任何大量更改。

历史

  • 2007 年 4 月 3 日 - 创建
  • 2007 年 4 月 11 日 - 修改以考虑根应用程序
© . All rights reserved.