且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

asp.net 4.0 Web 表单路由 - 默认/通配符路由

更新时间:2023-02-15 20:35:44

你可以像这样匹配所有剩余的路由:

You can match all remaining routes like this:

routes.MapPageRoute("defaultRoute", "{*value}", "~/Missing.aspx");

在这种情况下,我们知道所有路由,并希望将其他任何内容发送到丢失"/404 页面.请务必将此作为最后路由,因为它是一个通配符,可以捕获所有内容.

In this case, we know all routes, and want to send anything else to a "missing"/404 page. Just be sure to put this as the last route, since it is a wildcard and will catch everything.

或者,您可以以相同的方式注册路由,但在内部会映射到页面,如下所示:

Alternatively you could register a route the same way, but internally does mapping to a page, like this:

routes.Add(new Route("{*value}", new DefaultRouteHandler()));

那个处理程序类会做你的通配符映射,像这样:

That handler class would do your wildcard mapping, something like this:

public class DefaultRouteHandler : IRouteHandler
{
  public IHttpHandler GetHttpHandler(RequestContext requestContext)
  { 
    //Url mapping however you want here:
    var pageUrl = requestContext.RouteData.Route.Url + ".aspx";

    var page = BuildManager.CreateInstanceFromVirtualPath(pageUrl, typeof(Page)) 
               as IHttpHandler;
    if (page != null)
    {
      //Set the <form>'s postback url to the route
      var webForm = page as Page;
      if (webForm != null) 
         webForm.Load += delegate { webForm.Form.Action = 
                                    requestContext.HttpContext.Request.RawUrl; };
    }
    return page;
  }
}

为了防止水平滚动,这在奇怪的地方被打破了一点,但你得到了整体的观点.再次确保这是最后路由,否则它会处理所有你的路由.

This is broken a bit in odd places to prevent horizontal scrolling, but you get the overall point. Again, make sure this is the last route, otherwise it'll handle all your routes.