Web.config in sub directory doesn't work when using page routes

Viewed 504

I have an ASP.NET WebForms application with something along the lines of this file structure:

root\
  default.aspx
  web.config
  subfolder\
    page.aspx
    web.config

If I access page.aspx by going to locahost/subfolder/page.aspx it reads the web.config in the subfolder just fine.

However, I have a route to the page setup like so:

protected void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes(RouteTable.Routes);
}

public void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("", "test", "~/subfolder/page.aspx");
}

And when I try to access the page via that route, by going to localhost/test, the page loads just fine but it fails to read the values from the web.config in the sub folder.

Am I missing something? Is there some other step to allow a sub web.config to work with routes?

I'm accessing the sub web.config using:

var test = WebConfigurationManager.AppSettings["testSetting"];
1 Answers

I've been able to solve my issue by adding the following to my Global.asax:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpRequest request = HttpContext.Current.Request;
    Route route = RouteTable.Routes.Where(x => (x as Route)?.Url == request.Url.AbsolutePath.TrimStart('/')).FirstOrDefault() as Route;
    if (route != null)
    {
        if (route.RouteHandler.GetType() == typeof(PageRouteHandler))
        {
            HttpContext.Current.RewritePath(((PageRouteHandler)route.RouteHandler).VirtualPath, request.PathInfo, request.Url.Query.TrimStart('?'), false);
        }
    }
}

By doing this, I fake out the Url property of the Request object to use the "real" URL to the page for any request with a Url that matches an existing page route. This way, when WebConfigurationManager pulls up config (which it does by current virtual path), it pulls it up using the appropriate page.

Related