且构网

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

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

更新时间:2023-02-15 23:16:19

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

You can match all remaining routes like this:

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

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

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.