ASP.NET ASP 2 - Prioritize Routing?

天涯浪子 提交于 2021-01-29 03:51:13

问题


For a project, I'm having dynamic pages that are retrieved from a content database. However, some pages require some additional computing. So, I thought I'd create a specific controller/view for those, and they would only be hit when they exist, otherwise, my dynamic route would catch it, and let the content controller retrieve database content for the specified route. I hope I explained it right, but here's some code from my Global.asax that might explain it a bit more:

routes.MapRoute( // Default controller actions, when not found, fall back to next route?
                    "Default",                                              
                    "{controller}/{action}/{id}",                           
                    new { controller = "Home", action = "Index", id = "" }  
                );

routes.MapRoute( // Catch all other? (And try to find content for those)
                    "DefaultContentRoute",              
                    "{ContentCategory}/{Content}",                        
                    new { controller = "Content", action = "Index" },  
                );

This is obviously not working, as I get the "Multiple types were found that match the controller named xxx" error when I'm adding a controller for content that needs extra computing. But I was wondering if there is any other way to achieve what I am trying to do here? (Prioritizing routes) I obviously want to keep my URL completely dynamic.

Lot's of thanks in advance.


回答1:


ASP.NET MVC will be confused as any URL will match both routes. Try making one of the more explicit, such as:

routes.MapRoute( // Catch all other? (And try to find content for those) 
                    "DefaultContentRoute",               
                    "Categories/{ContentCategory}/{Content}",                         
                    new { controller = "Content", action = "Index" },   
                ); 

routes.MapRoute( // Default controller actions, when not found, fall back to next route? 
                    "Default",                                               
                    "{controller}/{action}/{id}",                            
                    new { controller = "Home", action = "Index", id = "" }   
                ); 

This will ensure any content will go through the default route, except for content that starts with "Categories" in the URL. An alternative may be to abuse route constraints, and create a constraint for your ContentController route that checks if the specified content exists or not.



来源:https://stackoverflow.com/questions/4647860/asp-net-asp-2-prioritize-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!