简体   繁体   中英

ASP.NET 4.0 webforms routing

I have an existing site that I'd like to convert to use routing, and after reading Scott Guthrie's post here , I built a working sample that works for most circumstances. However, since not all of the pages on the existing site match a particular pattern, I'll need to check against a database to determine which route (destination .aspx page) to use.

For example, most pages are like this:

http://www.mysite.com/people/person.html

This is fine - I can easily route these to the view_person.aspx page because of the 'people' directory.

But some pages are like this:

http://www.mysite.com/category_page.html http://www.mysite.com/product_page.html

This necessitates checking the database to see whether to route to the view_category.aspx page or the view_product.aspx page. And this is where I'm stuck. Do I create an IRouteHandler that checks the database and returns the route? Or is there a better way? The only code I've found that kind of fits is the answer to this question .

Thanks in advance.

If you don't mind doing so, the cleanest solution is to:

http://www.mysite.com/pages/category_page.html

In ASP.NET MVC, this situation would be handled a little differently, by specifying a default controller and action method on the root route.

Your route handler doesn't check the database. It sends all the requests to a handler .aspx script. It's that script that checks the database.

My register route looks like...

    private static void RegisterRoutes()
    {
        Route currRoute = new Route("{resource}.axd/{*pathInfo}", 
                                    new StopRoutingHandler());
        RouteTable.Routes.Add( "IgnoreHandlers", currRoute);

        currRoute = new Route("{urlname}",
                            new EPCRouteHandler("~/Default.aspx"));
        currRoute.Defaults = new RouteValueDictionary {{"urlname", "index.html"}};
        RouteTable.Routes.Add( "Default", currRoute);
    }

The custom handler, which shouldn't be needed in ASP.Net 4.0, simply passes the urlname parameter to the responding script as a URL variable.

Now how often the responding script checks the database depends on how often the data in the database is changed. You can easily cache paths and invalidate the cache when the data is suppose to have changed for instance.

对于陷入相同情况的任何人,我最终调整了这个答案中的代码来检查数据库并返回正确的ASPX页面。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM