WebForms 的路由如何显示 Google Adwords 查询字符串?

How can Routing for WebForms show a Google Adwords query string?

我已经用了将近 2 天了,我真的感觉卡住了。几年来,我一直是 运行 一个站点,使用 MapPageRoute 创建 url 数百个 "pages",这些都是由“~/default.aspx”通过数据库查找处理的用于页面数据。整个站点不是这样的(即它不是单页站点),但很大一部分是这样。

除了我无法在映射的路由上使用查询字符串外,它一直运行良好。 global.asax中的RegisterRoutes方法是:

   public static void RegisterRoutes(RouteCollection routes)
   {
      routes.Clear();
      routes.Ignore("{resource}.ashx/{*pathInfo}"); //ignore ashx files
      routes.Ignore("{resource}.axd/{*pathInfo}"); //ignore axd files, prevents javascript/routing collisions
      routes.MapPageRoute("SitePage", "{*page_url}", "~/default.aspx", false);
   }

我在路径段上使用了通配符。不幸的是,只允许使用一个通配符。 {*page_url} 通常表示 1 到 4 个段。我已经尝试了各种形式的 IRouteHandler 和 IHttpHandler 代码,但我不知道如何更改客户端浏览器中出现的 url。我可以这样使用通配符,因为 none 的路由会干扰物理文件。

我想保留查询字符串的唯一原因是 Google Adwords 向广告添加了一个 ?gclid=xxxxxxxxx 字符串 link,Google Analytics .js 使用该字符串要报告的查询字符串。

问题的示例 URL 描述是:

/about-us/community/philanthropy  (resolves fine)

/about-us/community/philanthropy?gclid=xxxxxxx  (redirects back to:)
/about-us/community/philanthropy

我的 web.config 没有 url - 重写可能影响此设置的设置。

我对 SO 和其他地方的大量研究都是针对 MVC 站点的。这是一个 WebForms 站点。

示例,类似问题,但针对 MVC: How do I route a URL with a querystring in ASP.NET MVC?

我为此完全放弃了路由引擎,转而重写路径。我的模式不适合路由。

我得到了 Chris Zhao 的帮助Is it possible to have Routing maintain a querystring in the browser address bar?

这个 link 对于更深入的上下文确实很有帮助:URL rewriting in an ASP.NET application

在 global.asax 在 Application_BeginRequest:

if (Request.CurrentExecutionFilePathExtension == "" && Request.CurrentExecutionFilePath != "/"
     && g.Global.SITEPAGEROOTS.ContainsKey(Request.Url.Segments[1].Replace("/", "")))
{
   Context.RewritePath("/default.aspx", false);
}

g.Global.SITEPAGEROOTS 是一个条目数小于 30 的字典单例,它只是挂在内存中直到垃圾回收。它包含需要 url-重写的我的网站页面的基本路径、主要 url 段。此外,"false" 关闭 rebaseClientPath,这有助于处理由于使用应用程序根目录引用 (~/) 而未在页面上显示的图像和其他项目。

在 /default.aspx 页面中:

var rawUri = new Uri(Request.Url, Request.RawUrl);
//using RawUrl because the url is usually rewritten before hitting this page
//and RawUrl preserves the original url.

if (rawUri.LocalPath != "/" && rawUri.LocalPath != "/default.aspx")
{
    //lookup the rawUri.LocalPath in the db and pull out all the site page
    //data needed to render the page (html, metas, etc.)
    //querystring found at rawUri.Query if needed.
}