加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 子目录中的Web.config在使用页面路由时不起作用

发布时间:2020-12-15 19:52:51 所属栏目:asp.Net 来源:网络整理
导读:我有一个ASP.NET WebForms应用程序,其中包含与此文件结构类似的内容: root default.aspx web.config subfolder page.aspx web.config 如果我通过访问locahost / subfolder / page.aspx来访问page.aspx,它会很好地读取子文件夹中的web.config. 但是,我有一
我有一个ASP.NET WebForms应用程序,其中包含与此文件结构类似的内容:
root
  default.aspx
  web.config
  subfolder
    page.aspx
    web.config

如果我通过访问locahost / subfolder / page.aspx来访问page.aspx,它会很好地读取子文件夹中的web.config.

但是,我有一个到页面设置的路径,如下所示:

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

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

当我尝试通过该路由访问页面时,通过转到localhost / test,页面加载得很好,但无法从子文件夹中的web.config读取值.

我错过了什么吗?是否有其他步骤允许子web.config使用路由?

我使用以下方法访问子web.config:

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

解决方法

我已经能够通过在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);
        }
    }
}

通过执行此操作,我伪造了Request对象的Url属性,以使用与网页匹配现有网页路由的任何请求的页面的“真实”URL.这样,当WebConfigurationManager提取配置(它通过当前虚拟路径执行)时,它会使用适当的页面将其拉出.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读