Web.config in a subdirectory does not work when using page routes

I have an ASP.NET WebForms application with something next to 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 web.config perfectly in the subfolder.

However, I have a way to customize the page:

 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 through this route by going to localhost/test , the page loads just fine, but cannot read the values ​​from web.config in a subfolder.

Am I missing something? Is there another step to let sub web.config work with routes?

I am accessing sub web.config using:

 var test = WebConfigurationManager.AppSettings["testSetting"]; 
+5
source share
1 answer

I managed to solve my problem 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, false); } } } 

In doing so, I distort the Url property of the Request object to use the "real" URL on the page for any request with a URL that matches the existing page route. Thus, when the WebConfigurationManager pulls out the configuration (which it performs on the current virtual path), it pulls it out using the corresponding page.

+3
source

Source: https://habr.com/ru/post/1273480/


All Articles