Asp.net路由屏蔽路径中的物理文件夹



为了更好地组织我的ASP。我把我所有的。aspx文件放在一个名为WebPages.

的文件夹中。

我想找到一种方法来掩盖'网页'文件夹从我所有的url。例如,我不想使用以下url:

http://localhost:7896/WebPages/index.aspx
http://localhost:7896/WebPages/Admin/security.aspx

但相反,我希望我所有的url如下('WebPages'是一个物理文件夹,我用来构建我的工作,但不应该是可见的外部世界):

http://localhost:7896/index.aspx
http://localhost:7896/admin/security.aspx

我能够想出一个我自己的解决方案,通过指定路由条目"为每个页面",我在我的项目(它工作),但这是根本不可维护的,我需要另一种方法。

public class Global : HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
    }
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("", "index.aspx", "~/WebPages/index.aspx");
        routes.MapPageRoute("", "admin/security.aspx", "~/WebPages/Admin/security.aspx");
    }
}

也许我之后是一个类捕获所有的请求,并简单地追加我的"网页"物理目录?

使用http://www.iis.net/download/urlrewrite this代替

你应该在你的web.config:

<rewrite>
  <rules>
    <rule name="Rewrite to Webpages folder">
      <match url="(.*)" />
      <action type="Rewrite" url="/WebPages/{R:1}" />
    </rule>
  </rules>
</rewrite>

我最终采用了以下解决方案,这对我的情况很有效:

在我的全局。我有以下代码:

public class Global : HttpApplication
{
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Request.Path.EndsWith(".aspx"))
        {
            FixUrlsForPages(Context, Request.RawUrl);
        }
    }
    private void FixUrlsForPages(HttpContext context, string url)
    {
        context.RewritePath("/WebPages" + url);
    }
}

它几乎做了Tudor所建议的,但在代码中而不是在web中。

最新更新